我有一个必填字段,字符串属性{get; set} 在一个类中,并希望在 razor 中设置它的值。类似下面的事情可能吗?
@model.attribute = "whatever'
最佳答案
首先,大小写很重要。
@model
(小写“m”)是 Razor View 中的保留关键字,用于在 View 顶部声明模型类型,例如:
@model MyNamespace.Models.MyModel
在文件的后面,您可以使用 @Model.Attribute
(大写“M”)引用所需的属性。
@model
声明模型。 Model
引用模型的实例化。
其次,您可以为模型分配一个值并稍后在页面中使用它,但当页面提交到 Controller 操作时,它不会持久,除非它是表单字段中的值。为了在模型绑定(bind)过程中将值返回到模型中,您需要将值分配给表单字段,例如:
选项 1
在 Controller 操作中,您需要为页面的第一个 View 创建一个模型,否则当您尝试设置 Model.Attribute
时,Model
对象将被空。
Controller :
// This accepts [HttpGet] by default, so it will be used to render the first call to the page
public ActionResult SomeAction()
{
MyModel model = new MyModel();
// optional: if you want to set the property here instead of in your view, you can
// model.Attribute = "whatever";
return View(model);
}
[HttpPost] // This action accepts data posted to the server
public ActionResult SomeAction(MyModel model)
{
// model.Attribute will now be "whatever"
return View(model);
}
查看:
@{Model.Attribute = "whatever";} @* Only do this here if you did NOT do it in the controller *@
@Html.HiddenFor(m => m.Attribute); @* This will make it so that Attribute = "whatever" when the page submits to the controller *@
选项 2
或者,由于模型是基于名称的,因此您可以跳过在 Controller 中创建模型,而只需将表单字段命名为与模型属性相同的名称。在这种情况下,将名为“Attribute”的隐藏字段设置为“whatever”将确保当页面提交时,值“whatever”将在模型绑定(bind)过程中绑定(bind)到模型的 Attribute
属性。请注意,它不必是隐藏字段,只需任何带有 name="Attribute"
的 HTML 输入字段即可。
Controller :
public ActionResult SomeAction()
{
return View();
}
[HttpPost] // This action accepts data posted to the server
public ActionResult SomeAction(MyModel model)
{
// model.Attribute will now be "whatever"
return View(model);
}
查看:
@Html.Hidden("属性", "无论什么");
关于asp.net-mvc-3 - 如何在razor View 中设置@model.attribute?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7562393/