gen*_*eek 38 razor asp.net-mvc-3
我有一个必填字段,字符串属性{get; 在一个类中设置}并希望在剃刀中设置它的值.是否有类似以下内容?
@model.attribute = "whatever'
Run Code Online (Sandbox Code Playgroud)
nek*_*kno 95
首先,资本化很重要.
@model
(小写"m")是Razor视图中的保留关键字,用于在视图顶部声明模型类型,例如:
@model MyNamespace.Models.MyModel
稍后在文件中,您可以引用所需的属性@Model.Attribute
(大写"M").
@model
宣布模型.Model
引用模型的实例化.
其次,您可以为模型分配一个值并在页面中稍后使用它,但是当页面提交到您的控制器操作时它将不会持久,除非它是表单字段中的值.为了在模型绑定过程中将值返回到模型中,您需要将值分配给表单字段,例如:
选项1
在控制器操作中,您需要为页面的第一个视图创建模型,否则在尝试设置时Model.Attribute
,该Model
对象将为null.
控制器:
// 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);
}
Run Code Online (Sandbox Code Playgroud)
视图:
@{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 *@
Run Code Online (Sandbox Code Playgroud)
选项2
或者,由于模型是基于名称的,因此您可以跳过在控制器中创建模型,并将表单字段命名为与模型属性相同的名称.在这种情况下,将名为"Attribute"的隐藏字段设置为"whatever"将确保在页面提交时,值"whatever"将Attribute
在模型绑定过程中绑定到模型的属性.请注意,它不必是隐藏字段,只需要任何HTML输入字段name="Attribute"
.
控制器:
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);
}
Run Code Online (Sandbox Code Playgroud)
视图:
@Html.Hidden("Attribute", "whatever");
归档时间: |
|
查看次数: |
85042 次 |
最近记录: |