当我打开此页面时(即使是第一次),我总是会收到验证消息,即使我在下拉列表中选择值,消息也不会消失。如果我在两者中都选择值,我可以提交表单,但消息仍然不会消失。
Snippet
是 Linq to sql 类并且LanguageID
是SnippetTypeID
整数,我假设发生这种情况是因为我将空模型传递给 View 所以LanguageID
并且SnippetTypeID
是 null 并且 AFAIK Linq to Sql 类需要不可为空的整数。
如何解决此问题,以便在用户尝试提交表单之前不会出现验证消息,并且如果选择下拉列表之一以删除验证消息。
看法
@model Data.Snippet
@using (Html.BeginForm("Save", "Submit", FormMethod.Post))
{
<h1 class="subtitle">Submit new snippet</h1>
<h4>Title</h4>
@Html.TextBoxFor(snippet => snippet.Title, new { @class = "form-field" })
<h4>Language</h4>
@Html.DropDownListFor(snippet => snippet.LanguageID, new SelectList(@ViewBag.Input.Languages, "ID", "Name", @Model.LanguageID), "Choose Language", new { @class = "form-select" })
<p>@Html.ValidationMessageFor(snippet => snippet.LanguageID , "You must choose language", new { @class= "validation-message"})</p>
<h4>Snipet type</h4>
@Html.DropDownListFor(snippet => snippet.SnippetTypeID, new SelectList(@ViewBag.Input.SnippetTypes, "ID", "Name", @Model.SnippetType), "Choose snippet type", new { @class = "form-select" })
<p>@Html.ValidationMessageFor(snippet => snippet.SnippetTypeID,"You must choose snippet type", new { @class= "validation-message"})</p>
<h4>Text</h4>
@Html.TextAreaFor(snippet => snippet.Text, new { cols = "20", rows = "10", @class = "form-field" })
<input type="submit" value="Submit Snippet" />
}
控制器
//Controllers are not finished Save() should have
//code to actually insert to db after I fix validation
// GET: /Submit/
//
public ActionResult Index()
{
Snippet model = new Snippet();
SubmitModel input = new SubmitModel();
ViewBag.Input = input;
return View(model);
}
public ActionResult Save(Snippet snippet)
{
return View();
}
模型
模型是 Linq to Sql 类。
Snippet
ID (int, identifier)
Title (string)
SnippetType (int, FK on table SnippetTypes)
LanguageID (int, FK on table Languages)
Text (string)