更新綁定視圖模型的隱藏字段。實例化視圖的ViewModel
讓我試着解釋我的情況。我可能完全錯誤,但這是我相信給我造成的問題。
我有一個視圖模型
項目創建視圖模型
[Bind(Exclude="List")]
public class ProjectCreateViewModel : ProjectViewModelBase
{
public CourseViewModelBase CourseVM { get; set; }
public ProjectCreateViewModel()
: base()
{
this.CourseVM = new CourseViewModelBase();
}
}
項目景觀示範基地是一個項目的基本視圖模型和所有相關的行動源於此,這樣我不需要一次又一次地寫出屬性名稱。
創建視圖模型庫與ProjectViewModelBase(由ProjectController處理或使用)類似,但是對於課程(由CourseController處理)類似。
現在我已經創建了一個形式「創建新項目」它採用ProjectCreateViewModel。然後在表格後動作CourseVM始終是null。
新建項目.cshtml
@model LMSPriorTool.ViewModels.ProjectCreateViewModel
@* --- labels and other stuff -- *@
@using (Html.BeginForm("CreateNewProject", "Project",
FormMethod.Post, new { @class = "form-horizontal",
name = "createNewProjectForm" }))
{
<!-- Hidden Fields -->
@Html.HiddenFor(x => x.ProjectId)
@Html.HiddenFor(x => x.CourseVM) // CourseVM is null in post action
@Html.TextBoxFor(x => x.CourseVM.CourseNumberRoot) // This is displayed properly
}
ProjectController
[HttpGet]
public ActionResult CreateNewProject(CourseViewModelBase courseVM = null)
{
ProjectCreateViewModel projectCreateViewModel = new ProjectCreateViewModel
{
CourseVM = courseVM,
};
// OTHER STUFF
return View("CreateNewProject", projectCreateViewModel);
}
錯誤 在HTTPPOST動作我得到CourseVM爲空,雖然我已經提供了它作爲一個隱藏的領域中的形式。
可能發行
我相信問題是與ProjectCreateViewModel的構造HTTPPOST動作發生時一樣,視圖將嘗試創建ProjectCreateViewModel的新實例,實例化CourseVM爲空。然後將相同的實例傳遞給其中CourseVM顯示爲null的HTTPPOST方法。
更新:問題根源原因複雜對象無法使用隱藏字段綁定到視圖模型。
任何建議或想法讚賞。
和那完美的工作。我認爲將整個「CourseVM」隱藏起來會創建新的courseVM對象。感謝有關「複雜對象不能綁定到隱藏的輸入字段」的信息 – Rohit