Question

I am working on an MVC 2.0 C# web Applciation. In one of my form, i am using LabelFor() html helper.

I am using the following syntax:

 <%=Html.LabelFor(model=>model.Addedon)%>

Here, for this label i would like to associate a initial value that is DateTime.Now

I tried some thing like this:

<%=Html.LabelFor(model=>model.Addedon,new{value=DateTime.Now})%>

But, i am getting an error saying that there is no over load for this helper taking two arguments.Please help

UPDATED:

The form is create form/ add form which makes an insert operation. So, i am building a model and updating that model to the database.

In that model, i have a field called createdby. So, i need to associate this value with the username logged in and doing the insert operation.

So, how to associate this username value with the model field and i need to display as label so that it will be read only field.

Hope this makes clear..

Was it helpful?

Solution

LabelFor is only for, you guessed it, rendering a <label> element. It also uses the [Display] and [DisplayName] attributes, so you can have a strongly-typed label with custom name.

What you're after is probably this:

<div>
    <%= Html.LabelFor(model => model.Addeon) %>
</div>
<div>
    <%= Html.DisplayFor(model => model.Addeon) %>
</div>

So the LabelFor will generate the property name description (e.g. 'Addeon'), while the DisplayFor will render the property value. DisplayFor can use the [DisplayFormat] attribute if you need custom formatting. You can set the default property value in the view model's constructor:

public class ViewModel
{
    [Display(Name = "My awesome date")]
    public DateTime Addeon {get;set;}

    public ViewModel()
    {
        Addeon = DateTime.Now;
    }
}

[EDIT]

Actually, your edit would make for a good second question instead of putting it here. Anyway, in your situation I'd create a dedicated view model that would hold the properties you need (e.g. user name) and would be filled in controller. Everything else would be conceptually the same - view would bind to the view model.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top