我有一個必填字段,字符串屬性{get;設置}在一個類中,並想在剃刀中設置它的值。是否有如下可能?如何在剃鬚刀視圖中設置@ model.attribute?
@model.attribute = "whatever'
我有一個必填字段,字符串屬性{get;設置}在一個類中,並想在剃刀中設置它的值。是否有如下可能?如何在剃鬚刀視圖中設置@ model.attribute?
@model.attribute = "whatever'
首先,大寫事項。
@model
(小寫字母「M」)是在剃刀意見保留關鍵字在您的視圖頂部申報型號,如:
@model MyNamespace.Models.MyModel
文件中以後,您可以參考你需要的屬性@Model.Attribute
(大寫字母「M」)。
@model
聲明瞭模型。 Model
引用模型的實例化。其次,您可以爲模型賦值並稍後在頁面中使用它,但當頁面提交給控制器操作時,除非它是表單字段中的值,否則它不會持久。爲了在模型綁定過程中得到值回你的模型,你需要的值賦給一個表單字段,如:
選項1
在你的控制器動作,您需要創建一個模型爲您的頁面的第一個視圖,否則當您嘗試設置Model.Attribute
時,Model
對象將爲空。
控制器:
// 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
或者,由於模型是基於域名的,則可以跳過創建在您的控制器型號和公正將表單字段命名爲與您的模型屬性相同的名稱。在這種情況下,將名爲「Attribute」的隱藏字段設置爲「whatever」將確保頁面提交時,值「whatever」將在模型綁定過程中綁定到您的模型的Attribute
屬性。請注意,它不一定是一個隱藏字段,只是任何帶有name="Attribute"
的HTML輸入字段。
控制器:
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("Attribute", "whatever");
感謝你爲這個。很好的答案。 – levteck
這個答案應該進入名人堂 – petric