有什么问题?模型始终为空。
控制器
[HttpGet]
public ViewResult Add()
{
return View("Edit");
}
[HttpPost]
public ViewResult Add(Models.EditViewModel m)
{
if (ModelState.IsValid)
{
return View("Success");
}
else
{
return View("Edit", m);
}
}
型号:
public class EditViewModel
{
[Required]
[Display(Name = "JobTitle", ResourceType = typeof(DisplayNames))]
public string Title { get; set; }
[Required]
[Display(Name = "JobDescription", ResourceType = typeof(DisplayNames))]
public string Description { get; set; }
}
查看
@model MyWebSite.Models.EditViewModel
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true, "Please correct the errors and try again.")
@Html.EditorForModel()
<input type="submit" value="Send" />
}
呈现视图
<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<form action="/MyAction" method="post"><div class="editor-label"><label for="Title">Função</label></div>
<div class="editor-field"><input class="text-box single-line" data-val="true" data-val-required="Informe um valor para Fun&#231;&#227;o" id="Title" name="Title" type="text" value="" /> <span class="field-validation-valid" data-valmsg-for="Title" data-valmsg-replace="true"></span></div>
<div class="editor-label"><label for="Description">Descrição</label></div>
<div class="editor-field"><input class="text-box single-line" data-val="true" data-val-required="Informe um valor para Descri&#231;&#227;o" id="Description" name="Description" type="text" value="" /> <span class="field-validation-valid" data-valmsg-for="Description" data-valmsg-replace="true"></span></div>
<input type="submit" value="Send" />
</form>
答案 0 :(得分:1)
知道了! 问题是每次都在创建一个新模型的坏道路。
<强>更改强>
routes.MapRoute(
"Add", // Route name
"AnnounceJob", // URL with parameters
new { controller = "Jobs", action = "Add", job = new Models.EditViewModel() } // Parameter defaults
);
要强>
routes.MapRoute(
"Add", // Route name
"AnnounceJob", // URL with parameters
new { controller = "Jobs", action = "Add", job = UrlParameter.Optional } // Parameter defaults
);