asp.net mvc: directly assign value to model inside

2019-05-10 23:11发布

问题:

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?

回答1:

You need to set the value of the property in the model before you pass the model to the view. Assuming your model is

public class ProductVM
{
    ....
    public decimal UnitPrice { get; set; }
}

then in the GET method

ProductVM model = new ProductVM()
{
    UnitPrice = 100M
};
return View(model);

If the value is a 'default' value that applies to all instances, you can also set its value in a parameter-less constructor

public class ProductVM
{
    public ProductVM()
    {
        UnitPrice = 100M;
    }
    ....
    public decimal UnitPrice { get; set; }
}

Note that the reason for the NullReferenceException is that you have not passed a model to your view.



回答2:

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..



回答3:

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
}