【问题标题】:asp.net mvc view only returns when using for loopasp.net mvc 视图仅在使用 for 循环时返回
【发布时间】:2017-04-11 13:58:07
【问题描述】:

所以我这周一直在开发一个简单的 asp.net 应用程序。今天我遇到了一个剃刀视图的问题,它没有向我的控制器方法返回任何内容。视图必须在 List 中返回多个对象。

我终于通过将对象列表传递给视图并使用“for”循环遍历它们来使其工作。我今天也尝试了 foreach 循环,但没有奏效。

我有以下 GET 方法将空对象列表传递给视图:

// GET: MpSwitches/CreateSeveral
    public ActionResult CreateSeveral()
    {
        var mpSwitches = new List<MpSwitch>
        {
            new MpSwitch() {IpAdress = "1"},
            new MpSwitch() {IpAdress = "2"},
            new MpSwitch() {IpAdress = "3"},
            new MpSwitch() {IpAdress = "4"},
            new MpSwitch() {IpAdress = "5"}
        };
        // Check if the user gets redirected to this method because of a First Time Startup.
        if (TempData["RedirectFirstTimeStartup"] != null)
        {
            ViewBag.FirstTime =
                "Je bent doorgestuurd naar deze pagina omdat er nog geen MP-switches in de database staan.";
            return View(mpSwitches);
        }
        return View(mpSwitches);
    }

然后是视图:

@model List<WebInterface.Models.MpSwitch>
@{
    ViewBag.Title = "Create several";
}
<h2>Create several</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>MpSwitch</h4>
        @if (ViewBag.FirstTime != null)
        {
            <div class="alert-warning">
                <b>Opgelet! </b>@ViewBag.FirstTime
            </div>
        }
        @for (int i = 0; i < Model.Count; i++)
        {
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model[i].IpAdress, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model[i].IpAdress, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model[i].IpAdress, "", new { @class = "text-danger" })
                </div>
            </div>
        }
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

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

我的问题是:为什么相同的代码不能使用“foreach”而不是“for”循环?

当前不工作的代码:

    @foreach (var item in Model)
    {
        <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger"})
            <div class="form-group">
            @Html.LabelFor(modelItem => item.IpAdress, htmlAttributes: new { 
    @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(modelItem => item.IpAdress, new { 
    htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(modelItem => item.IpAdress, "", new 
    { @class = "text-danger" })
            </div>
        </div>
    }

现在使用 foreach 循环时,以下控制器方法没有获取参数(参数为空)。

    // POST: MpSwitches/CreateSeveral
    // To protect from overposting attacks, please enable the specific 
    properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult CreateSeveral([Bind(Include = 
    "Id,IpAdress,LastSyncDateTime")] List<MpSwitch> mpSwitches)
    {
        if (ModelState.IsValid)
        {
            foreach (var mpSwitch in mpSwitches)
            {
                db.MpSwitches.Add(mpSwitch);
            }
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(mpSwitches);
    }

我收到以下错误:Link to image of my error

【问题讨论】:

  • 你能贴出不起作用的代码吗?
  • 用 foreach 编码!
  • 我添加了无效的代码
  • 你有什么错误吗?
  • 添加了我的错误截图的链接

标签: c# asp.net-mvc asp.net-mvc-4 razor data-binding


【解决方案1】:

如果你在使用foreach loop 时查看呈现的 html,你会得到这个

<input class="form-control text-box single-line" id="item_IpAdress" name="item.IpAdress" value="" type="text">

当你使用for loop 时会是这样的

<input class="form-control text-box single-line" id="MpSwitch_0__IpAdress" name="MpSwitch[0].IpAdress" value="" type="text">

因为您使用的是List&lt;MpSwitch&gt;,所以当您在MpSwitch[0].IpAdress 中使用for loop 提交表单时,IpAddress 的新值将被分配给index 0 上的MpSwitch,而在foreach loop 中的值将被分配到item.IpAdress,当您提交List&lt;MpSwitch&gt; 时将是null,因为要绑定复杂对象,您必须为每个项目提供一个索引。你也可以看看这个Model Binding To A List

【讨论】:

    【解决方案2】:

    您没有得到的原因是当您使用foreach 而不是for 时,您没有项目的索引并且HTML 元素的名称/ID 相互重叠。查看您发送到浏览器的 HTML 源代码(查看页面源代码或检查元素),您会注意到名称是 MpSwitch[0].IpAddress 等。当您使用 foreach 时,它只会是MpSwitch.IpAddress。不能将其序列化为集合。

    【讨论】:

      【解决方案3】:

      MVC ModelBinder 需要列表项的索引才能将它们正确绑定到 ViewModel。

      如果您使用for 循环,正确的索引将合并到生成的HTML &lt;input&gt; 元素的idname 属性中。

      您也可以显式合并索引,请参阅Binding arrays with missing elements in asp.net mvc

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-15
        • 1970-01-01
        • 2014-04-04
        相关资源
        最近更新 更多