开发者

Null and always valid model passed to action

What is wrong? Model is always null.

Controller

[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);
    }
}

Model:

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; }
}

View

@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" />
}

Rendered View

<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&#231;&#227;o</label></div>
    <div class="editor-field"><input class="text-box single-line" data-val="true" data-val-required="Informe um valor para Fun&amp;#231;&amp;#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&#231;&#227;o</label></div>
    <div class="editor-field"><input class="text-box single-line" data-val="true" data-val-required="Informe um valor para Descri&amp;#231;&amp;#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>


Got it! The problem was a bad route that was creating a new model everytime.

Changed

routes.MapRoute(
    "Add", // Route name
    "AnnounceJob", // URL with parameters
    new { controller = "Jobs", action = "Add", job = new Models.EditViewModel() } // Parameter defaults
);

To

routes.MapRoute(
    "Add", // Route name
    "AnnounceJob", // URL with parameters
    new { controller = "Jobs", action = "Add", job = UrlParameter.Optional } // Parameter defaults
);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜