Henrique Moreira
Henrique Moreira

Reputation: 93

ASP.NET MVC 4 - Set input value using @Html.EditorFor

Currently i have this field on a form:

@Html.EditorFor(model => model.AmountDecimal, 
  new { htmlAttributes = new { @class = "form-control" } })

But:

a) i want it to have the value "100" predefined

b) don't want it to be editable

I know how to do it in raw HTML but i need it to be in razor.

Thanks

Upvotes: 3

Views: 3502

Answers (2)

Pila 77
Pila 77

Reputation: 415

I think your are loooking for something like this:

@Html.EditorFor(model => model.AmountDecimal, 
  new { htmlAttributes = new { @class = "form-control", @Value = "100", @readonly = "readonly"} })

Upvotes: 1

pip
pip

Reputation: 116

It would make sense to set this value e.g. in the constructor of your model or in the controller before you call your view

public ActionResult MyAction()
{
    var model = new MyViewModel
    {
        AmountDecimal= 100
    };
    return View(model);
}

But if you really like to do it in razor, you may use HiddenFor

@Html.HiddenFor(model => model.AmountDecimal, new { @Value = "100" });
<input type="text" name = "dummy" class="form-control" value="100" readonly/>

Keep in mind to never trust a user input ;)

Upvotes: 3

Related Questions