asp.net mvc: directly assign value to model inside razor view

37,201

Solution 1

I think you may be trying to set value after textbox get loaded you need to first pass module from action like

"return View(objModel);"

and then you set value

"@Model.UnitPrice = 100;"

on top of your view and after write

"@Html.EditorFor(model => model.UnitPrice)"

code you will get value into editor. Thanks..

Solution 2

You need to pass the model's content like this on GET method:

public class ViewModel
{
    public ViewModel() 
    {
        UnitPrice = 100M;
    }
    ...
    // if you want constant read-only model in runtime, use readonly keyword before decimal and declare its constructor value
    public decimal UnitPrice { get; set; } 
}

[HttpGet]
public ActionResult YourView()
{
     ViewModel model = new ViewModel() 
     {
          model.Price = 100M; // if the property is not read-only
     };

     // other logic here

     return View(model);
}

// validation on server-side
[HttpPost]
public ActionResult YourView(ViewModel model)
{
    if (ModelState.IsValid)
    {
        // some logic here
    }

    // return type here
}
Share:
37,201
VSB
Author by

VSB

Updated on May 31, 2020

Comments

  • VSB
    VSB almost 4 years

    I have below snippet inside my Create razor View:

    @Html.EditorFor(model => model.UnitPrice)
    

    trying to directly set UnitPrice using statement like this:

    @Model.UnitPrice = 100;
    

    I got something like null pointer exception : Object reference not set to an instance of an object.

    How can I assign constant value to a field before posting to create post method?

  • Joseph Poirier
    Joseph Poirier about 5 years
    based on the original question, this is the only correct answer for the way it is written.