如果(ModelState.IsValid == false)返回View(); 或查看(模型);?

xpo*_*ort 10 asp.net-mvc asp.net-mvc-2

验证失败时,我应该返回哪一个?视图(); 或查看(模型); ?

我注意到这两个工作.这令人困惑.

编辑:

public class MoviesController : Controller
{
    MoviesEntities db = new MoviesEntities();

    //
    // GET: /Movies/

    public ActionResult Index()
    {
        var movies = from m in db.Movies
                     select m;
        return View(movies.ToList());
    }

    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Movie movie)
    {
        if (ModelState.IsValid)
        {
            db.AddToMovies(movie);
            db.SaveChanges();

            return RedirectToAction("Index");
        }
        else
            return View();//View(movie);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的Create.aspx:

<% using (Html.BeginForm()) {%>
    <%: Html.ValidationSummary(true) %>

    <fieldset>
        <legend>Fields</legend>


        <div class="editor-label">
            <%: Html.LabelFor(model => model.Title) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.Title) %>
            <%: Html.ValidationMessageFor(model => model.Title) %>
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.ReleaseDate) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.ReleaseDate) %>
            <%: Html.ValidationMessageFor(model => model.ReleaseDate) %>
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.Genre) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.Genre) %>
            <%: Html.ValidationMessageFor(model => model.Genre) %>
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.Price) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.Price) %>
            <%: Html.ValidationMessageFor(model => model.Price) %>
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>

<% } %>

<div>
    <%: Html.ActionLink("Back to List", "Index") %>
</div>
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 11

如果您要返回的视图是强类型并使用模型,则最好通过此模型.如果您只是return View()在视图中尝试访问模型,那么您很可能会得到一个NullReferenceException.

以下是一种常见模式:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = FetchModelFromRepo();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(SomeViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }        

        // TODO: update db
        return RedirectToAction("index");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @xport - HTML帮助程序不是强类型的.在这种特殊情况下,他们使用反射来反对它们传递的任何内容,以确定如何渲染它.但最终他们并不关心你的模特. (2认同)