Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.EditorFor Set Default Value

Rookie question. I have a parameter being passed to a create view. I need to set a field name with a default value. @Html.EditorFor(model => model.Id) I need to set this input field with name Id with a default value that is being passed to the view via an actionlink.

So, how can this input field [email protected](model => model.Id) -- get set with a default value.

Would the following work?? Where the number 5 is a parameter I pass into the text field to set default value.

@Html.EditorFor(c => c.PropertyName, new { text = "5"; })
like image 630
Nate Avatar asked May 19 '11 17:05

Nate


2 Answers

Here's what I've found:

@Html.TextBoxFor(c => c.Propertyname, new { @Value = "5" })

works with a capital V, not a lower case v (the assumption being value is a keyword used in setters typically) Lower vs upper value

@Html.EditorFor(c => c.Propertyname, new { @Value = "5" })

does not work

Your code ends up looking like this though

<input Value="5" id="Propertyname" name="Propertyname" type="text" value="" />

Value vs. value. Not sure I'd be too fond of that.

Why not just check in the controller action if the proprety has a value or not and if it doesn't just set it there in your view model to your defaulted value and let it bind so as to avoid all this monkey work in the view?

like image 190
Khepri Avatar answered Nov 01 '22 06:11

Khepri


The clean way to do so is to pass a new instance of the created entity through the controller:

//GET
public ActionResult CreateNewMyEntity(string default_value)
{
    MyEntity newMyEntity = new MyEntity();
    newMyEntity._propertyValue = default_value;

    return View(newMyEntity);
}

If you want to pass the default value through ActionLink

@Html.ActionLink("Create New", "CreateNewMyEntity", new { default_value = "5" })
like image 68
Shadi Avatar answered Nov 01 '22 07:11

Shadi