如何MVC填充模型时,数据被调回 [英] How does MVC populate the model when data is posted back

查看:81
本文介绍了如何MVC填充模型时,数据被调回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MVC是对如何将数据发送到浏览器很清楚。你去一个URL,它运行code创建一个模型,通过该类型模型到视图,然后基于该模型的状态呈现HTML。

什么我没有找到那么清楚不过当用户提交页面上的形式是,如何MVC映射表邮寄回模型控制器使用?

我猜魔术发生在某处:

  @ Html.EditorFor(型号=> model.Title)

但我不明白为什么....

我在下面的开始使用ASP.NET MVC 3 。这哪里是code以下为便于参考。

控制器:

 公众的ActionResult编辑(INT ID)
{
    电影电影= db.Movies.Find(ID);
    返回查看(电影);
}[HttpPost]
公众的ActionResult编辑(动画电影)
{
    如果(ModelState.IsValid)
    {
        db.Entry(电影).STATE = EntityState.Modified;
        db.SaveChanges();
        返回RedirectToAction(「指数」);
    }
    返回查看(电影);
}

查看:

  @model MvcMovie.Models.Movie@ {
    ViewBag.Title =编辑;
}< H2>编辑< / H><脚本的src =@ Url.Content(〜/脚本/ jquery.validate.min.js)TYPE =文/ JavaScript的>< / SCRIPT>
<脚本的src =@ Url.Content(〜/脚本/ jquery.validate.unobtrusive.min.js)TYPE =文/ JavaScript的>< / SCRIPT>@using(Html.BeginForm()){
    @ Html.ValidationSummary(真)
    <&字段集GT;
        <传奇>电影< /传说>        @ Html.HiddenFor(型号=> model.ID)        < D​​IV CLASS =编辑标记>
            @ Html.LabelFor(型号=> model.Title)
        < / DIV>
        < D​​IV CLASS =主编场>
            @ Html.EditorFor(型号=> model.Title)
            @ Html.ValidationMessageFor(型号=> model.Title)
        < / DIV>        < D​​IV CLASS =编辑标记>
            @ Html.LabelFor(型号=> model.ReleaseDate)
        < / DIV>
        < D​​IV CLASS =主编场>
            @ Html.EditorFor(型号=> model.ReleaseDate)
            @ Html.ValidationMessageFor(型号=> model.ReleaseDate)
        < / DIV>        < D​​IV CLASS =编辑标记>
            @ Html.LabelFor(型号=> model.Genre)
        < / DIV>
        < D​​IV CLASS =主编场>
            @ Html.EditorFor(型号=> model.Genre)
            @ Html.ValidationMessageFor(型号=> model.Genre)
        < / DIV>        < D​​IV CLASS =编辑标记>
            @ Html.LabelFor(型号=> model.Price)
        < / DIV>
        < D​​IV CLASS =主编场>
            @ Html.EditorFor(型号=> model.Price)
            @ Html.ValidationMessageFor(型号=> model.Price)
        < / DIV>        &所述p为H.;
            <输入类型=提交值=保存/>
        &所述; / P>
    < /字段集>
}< D​​IV>
    @ Html.ActionLink(返回目录,索引)
< / DIV>

生成:

 <!DOCTYPE HTML>
< HTML和GT;
< HEAD>
    <间的charset =UTF-8/>
    <标题>编辑< /标题>
    <链接HREF =/内容/的site.css的rel =stylesheet属性类型=文/ CSS/>
    <脚本的src =/脚本/ jQuery的-1.5.1.min.js类型=文/ JavaScript的>< / SCRIPT>
    <脚本的src =/脚本/ Modernizr的-1.7.min.js类型=文/ JavaScript的>< / SCRIPT>
< /头>
<身体GT;
    < D​​IV CLASS =页>
        <报头GT;
            < D​​IV ID =标题>
                < H1> MVC应用程序电影和LT; / H1>
            < / DIV>
           ...
        < /头>
        <节ID =主>
< H2>编辑< / H><脚本的src =/脚本/ jquery.validate.min.js类型=文/ JavaScript的>< / SCRIPT>
<脚本的src =/脚本/ jquery.validate.unobtrusive.min.js类型=文/ JavaScript的>< / SCRIPT><形式的行动=/电影/编辑/ 4的方法=后> <&字段集GT;
        <传奇>电影< /传说>        <输入数据-VAL =真正的数据-VAL-数=字段ID必须是数字。
                数据-VAL-需要=是必需的ID字段。 ID =IDNAME =ID类型=隐藏值=4/>        < D​​IV CLASS =编辑标记>
            <标签=标题>标题< /标签>
        < / DIV>
        < D​​IV CLASS =主编场>
            <输入类=文本框单行ID =标题名称=标题类型=文本VALUE =布拉沃/>
            <跨度类=现场验证,有效的数据valmsg换=标题数据valmsg替换=真正的>< / SPAN>
        < / DIV>        < D​​IV CLASS =编辑标记>
            <标签=RELEASEDATE>&RELEASEDATE LT; /标签>
        < / DIV>
        < D​​IV CLASS =主编场>
            <输入级=数据-VAL =真正的数据-VAL-需要文本框单行=是必需的RELEASEDATE场。
                ID =RELEASEDATENAME =RELEASEDATE类型=文本值=1959年4月15日上午12点00分00秒/>
            <跨度类=现场验证,有效的数据valmsg换=RELEASEDATE数据valmsg替换=真正的>< / SPAN>
        < / DIV>        < D​​IV CLASS =编辑标记>
            <标签=类型>类型< /标签>
        < / DIV>
        < D​​IV CLASS =主编场>
            <输入类=文本框单行ID =体裁NAME =流派类型=文本值=西方/>
            <跨度类=现场验证,有效的数据valmsg换=体裁数据valmsg替换=真正的>< / SPAN>
        < / DIV>        < D​​IV CLASS =编辑标记>
            <标签=价格>价格< /标签>
        < / DIV>
        < D​​IV CLASS =主编场>
            <输入类=文本框单行数据-VAL =真正的数据-VAL-数=这个领域的价格必须是一个数字。
                数据-VAL-所需=是必需的价格区域。 ID =价格NAME =价格型=文本值=9.99/>
            <跨度类=现场验证,有效的数据valmsg换=价格数据valmsg替换=真正的>< / SPAN>
        < / DIV>        &所述p为H.;
            <输入类型=提交值=保存/>
        &所述; / P>
    < /字段集>
< /表及GT;
< D​​IV>
    < A HREF =/电影>返回列表< / A>
< / DIV>        < /节>
        <页脚GT&;
        < /页脚>
    < / DIV>
< /身体GT;
< / HTML>


解决方案

MVC只是相匹配的模型的公共属性对同名的FormsCollection对象值。如果有名称和类型的匹配,则该模型的一个实例是创建和的值复制到这些属性

这过程被称为模型绑定的,你可以创建自定义模型绑定。

这个过程有一点直接与EditorFor做,虽然EditorFor使用模板,确保的方式,模型绑定能理解来命名表单输入。

MVC is very clear on how data is sent to the browser. You go to a URL, it runs code to create a model, passes that typed model into a view, which then renders HTML based on the state of the model.

What I'm not finding so clear however is when a user submits a form on the page, how does MVC map that form post back to the model for use in the controller?

I'm guessing the magic happens somewhere in:

@Html.EditorFor(model => model.Title)

But I'm not understanding why....

I'm following Getting started with ASP.NET MVC 3. Which is where the code below is from for easy reference.

Controller:

public ActionResult Edit(int id) 
{
    Movie movie = db.Movies.Find(id);
    return View(movie);
}

[HttpPost]
public ActionResult Edit(Movie movie)
{
    if (ModelState.IsValid) 
    {
        db.Entry(movie).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(movie);
}

View:

@model MvcMovie.Models.Movie

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

<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)
    <fieldset>
        <legend>Movie</legend>

        @Html.HiddenFor(model => model.ID)

        <div class="editor-label">
            @Html.LabelFor(model => model.Title)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Title)
            @Html.ValidationMessageFor(model => model.Title)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ReleaseDate)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ReleaseDate)
            @Html.ValidationMessageFor(model => model.ReleaseDate)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Genre)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Genre)
            @Html.ValidationMessageFor(model => model.Genre)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Price)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Price)
            @Html.ValidationMessageFor(model => model.Price)
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

Which generates:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Edit</title>
    <link href="/Content/Site.css" rel="stylesheet" type="text/css" />
    <script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
    <script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
</head>
<body>
    <div class="page">
        <header>
            <div id="title">
                <h1>MVC Movie App</h1>
            </div>
           ...
        </header>
        <section id="main">


<h2>Edit</h2>

<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="/Movies/Edit/4" method="post">    <fieldset>
        <legend>Movie</legend>

        <input data-val="true" data-val-number="The field ID must be a number." 
                data-val-required="The ID field is required." id="ID" name="ID" type="hidden" value="4" />

        <div class="editor-label">
            <label for="Title">Title</label>
        </div>
        <div class="editor-field">
            <input class="text-box single-line" id="Title" name="Title" type="text" value="Rio Bravo" />
            <span class="field-validation-valid" data-valmsg-for="Title" data-valmsg-replace="true"></span>
        </div>

        <div class="editor-label">
            <label for="ReleaseDate">ReleaseDate</label>
        </div>
        <div class="editor-field">
            <input class="text-box single-line" data-val="true" data-val-required="The ReleaseDate field is required." 
                id="ReleaseDate" name="ReleaseDate" type="text" value="4/15/1959 12:00:00 AM" />
            <span class="field-validation-valid" data-valmsg-for="ReleaseDate" data-valmsg-replace="true"></span>
        </div>

        <div class="editor-label">
            <label for="Genre">Genre</label>
        </div>
        <div class="editor-field">
            <input class="text-box single-line" id="Genre" name="Genre" type="text" value="Western" />
            <span class="field-validation-valid" data-valmsg-for="Genre" data-valmsg-replace="true"></span>
        </div>

        <div class="editor-label">
            <label for="Price">Price</label>
        </div>
        <div class="editor-field">
            <input class="text-box single-line" data-val="true" data-val-number="The field Price must be a number." 
                data-val-required="The Price field is required." id="Price" name="Price" type="text" value="9.99" />
            <span class="field-validation-valid" data-valmsg-for="Price" data-valmsg-replace="true"></span>
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
</form>
<div>
    <a href="/Movies">Back to List</a>
</div>

        </section>
        <footer>
        </footer>
    </div>
</body>
</html>

解决方案

MVC just matches the public properties of a model against values in the FormsCollection object of the same name. If there is a match of name and type, then an instance of the model is created and the values copied into those properties.

This process is called Model Binding, and you can create custom Model Binders.

The process has little to do with EditorFor directly, although EditorFor uses templates that make sure to name the form inputs in a manner that the model binder can understand.

这篇关于如何MVC填充模型时,数据被调回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆