[英]asp.net mvc: directly assign value to model inside razor view
我在Create razor里面有以下片段视图:
@Html.EditorFor(model => model.UnitPrice)
尝试使用如下语句直接设置UnitPrice
:
@Model.UnitPrice = 100;
我有类似空指针异常的东西: Object reference not set to an instance of an object.
如何在发布创建post方法之前为字段分配常量值?
在将模型传递给视图之前,需要在模型中设置属性的值。 假设你的模型是
public class ProductVM
{
....
public decimal UnitPrice { get; set; }
}
然后在GET方法中
ProductVM model = new ProductVM()
{
UnitPrice = 100M
};
return View(model);
如果该值是适用于所有实例的“默认”值,则还可以在无参数构造函数中设置其值
public class ProductVM
{
public ProductVM()
{
UnitPrice = 100M;
}
....
public decimal UnitPrice { get; set; }
}
请注意, NullReferenceException
的原因是您尚未将模型传递给视图。
我想你可能正试图在文本框加载后设置值,你需要首先从动作中传递模块
“return View(objModel);”
然后你设定价值
“@ Model.UnitPrice = 100;”
在你的观点之上和写完之后
“@ Html.EditorFor(model => model.UnitPrice)”
代码,你将获得编辑器的价值。 谢谢..
您需要在GET方法上传递模型的内容:
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.