asp.net-mvccssasp.net-mvc-4razorgenerator

Setting value for a textbox MVC 4 ASP


I have the following code in my view .cshtml

...
<td class="Centrado">
<input class="plato" value="" id="TComida">                                                                                
</td>
....

and i want to set a value that comes from the controller, the value is from the class Comida the property Price,

....
@model Util.Comida
Util.Comida menu = new Util.Comida();
menu= (Util.Comida)ViewData["Comida"];
....

¿What can i do to set the value menu.Price to my input class="plato" value="" id="TComida" without losing the css styles aplied thx to my class="plato"?

I have checked that the object menu is correctly populated with data from the controller. Sorry for my english and thx in advance.


Solution

  • This isn't really what you should be doing in a view:

    @model Util.Comida
    Util.Comida menu = new Util.Comida();
    menu= (Util.Comida)ViewData["Comida"];
    

    If the model is a Util.Comida then the controller should supply an instance of one to the view. For example, when returning the view in the controller:

    var model = new Util.Comida();
    // set properties, invoke logic, etc.
    return View(model);
    

    Then in the view the model is inherently present in the Model property. So use one of its values, you can reference that property. For example:

    <input class="plato" value="@Model.Price" id="TComida">
    

    Or even use an HTML helper to emit the input tag, which can bring more framework functionality with it. Something like this:

    @Html.TextBoxFor(m => m.Price, new { id = "TComida", @class = "plato" })
    

    The point is that the controller provides the view with the model, the view doesn't create the model or invoke any logic on it. Code in a view should generally be limited to binding to properties on a model. Actual logic goes in the model, and the controller invokes that logic and provides the resulting model state to the view.