ASP.NETMVC:为什么我的视图将空模型传递回我的控制器?

ASP.NETMVC:为什么我的视图将空模型传递回我的控制器?

我不明白为什么我的视图只将模型的NULL传递给我的控制器。这是一个编辑后的方法。我用EditPost方法检查了其他控制器,这些方法的结构与这个方法相同,它们工作得很好。它似乎只是这个观点和控制器。

以下是我的看法:

@model Non_P21_Quote_System_v1._0.Models.gl_code@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";}<h2>Edit</h2>@if (TempData["Message"] != null){
    <div style="color:green">
        @TempData["Message"]
    </div><br />}@if (ViewBag.error != null){
    <div style="color:red">
        <h3>@ViewBag.error</h3>
    </div><br />}@using (Html.BeginForm()){
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>gl_code</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.ID)

        <div class="form-group">
            @Html.LabelFor(model => model.GL_code, "GL Code", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.GL_code, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.GL_code, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.GL_description, "Gl Description", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.GL_description, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.GL_description, "", new { @class = "text-danger" })
            </div>
        </div>


调试它时,我看到传入的模型值为NULL。我在控制器端看到了这一点,在编辑方法的参数部分。


凤凰求蛊
浏览 528回答 2
2回答

qq_花开花谢_0

它为空,因为您的模型包含一个名为gl_code您还为您的模型命名了参数gl_code在后置法中。更改其中一个或另一个的名称,模型将正确绑定。在内部发生的情况是,在您的示例中,表单为每个成功的窗体控件提交一个名称/值对。gl_code=someValue..这个DefaultModelBinder首先初始化模型的新实例。然后,它读取表单值,并为模型中的属性找到匹配项,并将其设置为someValue..但是,它也会在方法参数中找到匹配项,并尝试将参数的值设置为someValue失败(因为您不能这样做)。gl_code gl_code = "someValue";)而模型变成null.

慕莱坞森

视图模型上似乎有一个名为gl_code的属性。在控制器中,还将视图模型称为gl_code。试着改变这个。public&nbsp;async&nbsp;Task<ActionResult>&nbsp;Edit(gl_code&nbsp;gl_code)到public&nbsp;async&nbsp;Task<ActionResult>&nbsp;Edit(gl_code&nbsp;model)
打开App,查看更多内容
随时随地看视频慕课网APP