[英]MVC.NET the ViewModel from Create POST is always null
在我的MVC.NET項目中,我使用了腳手架模板。 最初將其綁定到一個DTO模型。 現在我決定將它鏈接到ViewModel,因為我需要使用兩個多重選擇來傳遞值。 這就是我的ViewModel的樣子:
public class CreateQuestionModel
{
public Question Question { get; set; }
public List<int> PoliticianIds { get; set; }
public List<int> TopicIds { get; set; }
}
我的創建POST方法從View中獲取ViewModel:
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Regular")]
public ActionResult Create(CreateQuestionModel question)
{
if (ModelState.IsValid)
{
int id = WebSecurity.CurrentUserId;
manager.CreateQuestion(question.Question, id, question.PoliticianIds, question.TopicIds);
return RedirectToAction("Index");
}
return View(question);
}
我的Create.cshtml看起來像這樣:
@model PoliticiOnline.Models.CreateQuestionModel
@{
ViewBag.Title = "Stel een vraag!";
}
<head>
<link rel="stylesheet" href="~/Content/Questions.css" type="text/css" />
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
<script src="@Url.Content("~/Scripts/Extra/Chosen/chosen.jquery.min.js")" type="text/javascript"></script>
<link rel="stylesheet" href="@Url.Content("~/Scripts/Extra/Chosen/chosen.min.css")" type="text/css">
<script src="@Url.Content("~/Scripts/Extra/select2-3.4.6/select2.min.js")" type="text/javascript"></script>
<link rel="stylesheet" href="@Url.Content("~/Scripts/Extra/select2-3.4.6/select2.css")" type="text/css">
</head>
<h2>Stel een vraag!</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Vraag</legend>
<div class="general-question">
<div class="editor-label">
@Html.LabelFor(model => model.Question.GeneralQuestion, "Algemene Vraag")
</div>
<div class="editor-field">
@Html.TextBox("Question.GeneralQuestion", new { @class = "general-question-edit" })
@Html.ValidationMessageFor(model => model.Question.GeneralQuestion)
</div>
</div>
<div id="geadresseerde-politici">
@Html.LabelFor(model => model.PoliticianIds, "Geadresseerde Politicians:")
@Html.ListBox("PoliticianIds", (MultiSelectList)ViewBag.Politicians, new { @id = "polDrop" })
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Question.Explanation, "Extra Uitleg")
</div>
<div class="editor-field">
@Html.TextArea("Question.Explanation", new { @class = "explanation-textarea-edit" })
@Html.ValidationMessageFor(model => model.Question.Explanation)
</div>
<div>
@Html.LabelFor(model => model.TopicIds, "Kies je thema's (maximum 2):")
@Html.ListBox("TopicIds", (MultiSelectList)ViewBag.Topics, new { @id = "select2select", @style = "width: 500px"})
</div>
<p>
<input type="submit" value="Indienen!" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
<script type="text/javascript">
function format(topic) {
if (topic.css == 'optionGroup') {
return "<b>" + topic.text + "</b>";
} else {
return "<i> " + topic.text + "<i>";
}
}
$("#select2select").select2({
placeholder: "Selecteer een thema...",
maximumSelectionSize: 2,
formatResult: format,
escapeMarkup: function(m) {
return m;
}
});
</script>
底部的<script>
部分並不重要,但無論如何我都粘貼了它,我正在使用jQuery插件select2作為ListBox。
這是一種將文本框綁定到ViewModel屬性的方法,我在Stackoverflow上發現了這一點。 我還嘗試使用@Html.EditorFor
和@HtmlListBoxFor
的經典方法,但ViewModel的屬性始終為null。
我做錯了什么/我在俯視什么?
編輯:我在ViewModel中放置了一個構造函數,現在ViewModel(CreateQuestionModel)不再為null,但值仍然是默認值(不是表單中的值)。 我的ViewModel現在看起來像:
public class CreateQuestionModel
{
public Question Question { get; set; }
public List<int> PoliticianIds { get; set; }
public List<int> TopicIds { get; set; }
public CreateQuestionModel()
{
Question = new Question();
PoliticianIds = new List<int>();
TopicIds = new List<int>();
}
}
解決方案評論者Yoeri提供了解決方案,您可以在我對這個問題的回答中看到它!
我的啞錯誤導致ViewModel
中的所有屬性成為POST到Controller
默認值。 我沒有聲明{get; set;}
為每個屬性{get; set;}
錯誤
public class ApplicationViewModel
{
public Application App;
public SelectList SelectSimple;
public ApplicationViewModel()
{
// Create/Init App & SelectSimple
}
}
正確
public class ApplicationViewModel
{
public Application App { get; set; }
public SelectList SelectSimple { get; set; }
public ApplicationViewModel()
{
// Create/Init App & SelectSimple
}
}
評論
需要重復的是,Controller需要一個將非空ViewModel傳遞給View的[HttpGet]; 和Controller需要一個[HttpPost]來接收用戶提交的ViewModel。
好吧,伙計們,我剛剛發現了我做錯了什么。 我犯了一個非常愚蠢的錯誤,不敢相信我現在已經用這個奮斗了2天。
我的Create POST方法的簽名是:
public ActionResult Create(CreateQuestionModel question)
{
...
}
它應該是:
public ActionResult Create(CreateQuestionModel createQuestionModel)
{
...
}
我只需要將參數表單CreateQuestionModel question
更改為CreateQuestionModel createQuestionModel
,就像那樣簡單,現在一切正常。
更新感謝Yoeri我現在明白為什么它首先提出問題:
最初我將參數命名為CreateQuestionModel question
,這沒有用,因為我有一個名為Question
的模型類。 所以基本上參數名稱必須是您在創建視圖中使用的模型的名稱,或者任何其他名稱,只要它不是另一個模型類的名稱!
謝謝Yoeri!
嘗試,
@using(Html.BeginForm("Create", "*controller-name*",FormMethod.Post))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.