不要使用域模型視圖。創建一個新的POCO類是特定於您的視圖。一般來說,我們稱之爲ViewModel。
public class ChamodoVM
{
[Required]
public string ChamdoName { set;get;}
[Required]
public string InteracoName { set;get;}
//other properties here as needed
}
現在YOUT GET
動作創建該類的一個對象,並傳遞給View
方法。
public ActionResult Create()
{
var vm=new ChamodoVM();
return View(vm);
}
將您的視圖強制鍵入ViewModel類。
@model ChamodoVM
@using(Html.BeginForm())
{
@Html.LabelFor(x=>x.ChamodoName)
@Html.TextBoxFor(x=>x.ChamodoName)
@Html.LabelFor(x=>x.InteracoName)
@Html.TextBoxFor(x=>x.InteracoName)
<input type="submit" />
}
當用戶提交表單時,請從視圖模型中讀取值並將其分配給您的域模式的對象並保存。感謝MVC模型綁定。 :)
[HttpPost]
public ActionResult Create(ChamodoVM model)
{
if(ModelState.IsValid)
{
var domainModel=new Chamodo();
domainModel.Name=model.ChamodoName;
domainModel.Interaco=new Interaco();
domainModel.Interaco.Name=model.InteracoName;
yourRepositary.SaveClient(domainModel);
//If saved successfully, Redirect to another view (PRG pattern)
return RedirectToAction("ChamodoSaved");
}
return View(model);
}
請提供表名稱和列名稱,並說明您希望從UI推送到數據庫表中的哪個數據。 –
什麼是你的數據庫? –