Davood
Davood

Reputation: 5635

how to pass default value to textbox dynamically?

mvc3 razor- i have a bellow model in my web app:

public class mymodel{

    [Display(Name = "name")]
    public string Name { get; set; }
}

when we use

 @Html.LabelFor(m => m.Name) 

it use display "name" ,for example upper of our text box to show user this filed is for entering your name.

how can i use display name in text box value? i test it but value is empty i want to get value from my model from [Display(Name = "name")]

 @Html.TextBoxFor(m => m.Name, new {@Value = @Html.ValueFor(m => m.Name)})

Upvotes: 0

Views: 2003

Answers (2)

Lee Bailey
Lee Bailey

Reputation: 3624

@Html.TextBoxFor(m => m.Name, new {Value = Html.DisplayNameFor(m => m.Name)})

EDIT: If you need to re-display the form and preserve the value that the user entered, then you might want to either use Darin's approach, or do something like this:

@Html.TextBoxFor(m => m.Name, new { Value = (string.IsNullOrWhiteSpace(Model.Name) ? Html.DisplayNameFor(x => x.Name).ToHtmlString() : Model.Name) })

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1038750

In the controller action rendering this view you could set the Name property of your view model:

public ActionResult Index()
{
    var model = new MyViewModel();
    model.Name = ModelMetadata.FromLambdaExpression<MyViewModel, string>(x => x.Name, new ViewDataDictionary<MyViewModel>(model)).DisplayName;
    return View(model);
}

and in your view:

@Html.LabelFor(x => x.Name)
@Html.EditorFor(x => x.Name)

Upvotes: 0

Related Questions