Asp.net-Mvc
發布具有多個部分視圖的表單
我目前正在嘗試發布一個由兩個強類型視圖組成的表單。這個問題很相似,但沒有答案:
MVC 3 Razor 表單發布,帶多個強類型的部分視圖不綁定
當我送出表單時,送出給控制器的模型始終為空。我花了幾個小時試圖讓它工作。這似乎應該很簡單。我在這裡錯過了什麼嗎?我不需要做 ajax 只需要能夠發佈到控制器並呈現一個新頁面。
謝謝
這是我的視圖程式碼:
<div> @using (Html.BeginForm("TransactionReport", "Reports", FormMethod.Post, new {id="report_request"})) { ViewContext.FormContext.ValidationSummaryId = "valSumId"; @Html.ValidationSummary(false, "Please fix these error(s) and try again.", new Dictionary<string, object> { { "id", "valSumId" } }); @Html.Partial("_ReportOptions", Model.ReportOptions); @Html.Partial("_TransactionSearchFields", new ViewDataDictionary(viewData) { Model = Model.SearchCriteria }); }這是控制器中的程式碼:
[AcceptVerbs(HttpVerbs.Post)] public ActionResult TransactionReport(TransactionReportRequest reportRequest) { var reportInfo = new List<TransactionReportItem>(); if (ModelState.IsValid) { var reportData = _reportDataService.GetReportData(Search.MapToDomainSearchCriteria(reportRequest.SearchCriteria)); if (reportData!=null) { reportInfo = reportData.ToList(); } return View(reportInfo); } return View(reportInfo); }部分視圖本身是無關緊要的,因為他們所做的只是投標和展示他們的模型。
部分不是這裡的方式。您正在尋找 EditorTemplates,這些都是為您想要的。在這種情況下,您的屬性將很好地綁定到您的模型(您將送出)。
您的主視圖將具有這種形式(請注意,您只需要使用
EditorFor而不是Partial;在這種情況下,您可能需要將該 viewData 參數放在 ViewBag 左右):@using (Html.BeginForm("TransactionReport", "Reports", FormMethod.Post, new {id="report_request"})) { ViewContext.FormContext.ValidationSummaryId = "valSumId"; @Html.ValidationSummary(false, "Please fix these error(s) and try again.", new Dictionary<string, object> { { "id", "valSumId" } }); @Html.EditorFor(model => model.ReportOptions); @Html.EditorFor(model = Model.SearchCriteria }); }現在您只需將您的部分拖到文件夾
~/Shared/EditorTemplates/並重命名它們以匹配它們作為編輯器模板的模型名稱。在
~/Shared/EditorTemplates/文件夾中,創建一個新的“視圖”,例如“SearchCriteria.cshtml”。在裡面,將您要為其創建編輯器模板的類的類型作為“模型”。範例(範例類具有屬性Name和OtherCriteria):@model MyNamespace.SearchCriteria <ul> <!-- Note that I also use EditorFor for the properties; this way you can "nest" editor templates or create custom editor templates for system types (like DateTime or String or ...). --> <li>@Html.LabelFor(m => m.Name): @Html.EditorFor(m => m.Name)</li> <li>@Html.LabelFor(m => OtherCriteria): @Html.EditorFor(m => m.OtherCriteria</li> </ul>一些關於它們的好讀物:
- <https://www.exceptionnotfound.net/asp-net-mvc-demystified-display-and-editor-templates/>
- <https://www.hanselman.com/blog/ASPNETMVCDisplayTemplateAndEditorTemplatesForEntityFrameworkDbGeographySpatialTypes.aspx>