【问题标题】:Form submit using partail View error使用部分视图错误提交表单
【发布时间】:2016-06-16 09:08:42
【问题描述】:

我创建了一个用于添加评论的表单。我在 Home 控制器中名为 Index 的主视图中创建了它。下面是索引视图

private projectDBEntities db = new projectDBEntities();
    public ActionResult Index()
    {
        ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

        return View();
    }

    public ActionResult AddComment()
    {
        return PartialView("_Comment");
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult AddComment(comment cmt)
    {
        if (ModelState.IsValid)
        {
            db.comments.Add(cmt);
            db.SaveChanges();
            return RedirectToAction("Index", "Home");
        }
        return PartialView("_Comment", cmt);
    }

下面是_评论部分视图

@using (Html.BeginForm()) {@Html.AntiForgeryToken()@Html.ValidationSummary(true)
<fieldset>
    <legend>comment</legend>

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

    <div class="editor-label">
        @Html.LabelFor(model => model.t_email)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.t_email)
        @Html.ValidationMessageFor(model => model.t_email)
    </div>
    <p>
        <input type="submit" value="Comment" />
    </p>
</fieldset>}

发生了 System.Web.HttpException。我想知道这个错误背后的原因是什么以及使用部分视图提交表单的最佳方法是什么。

【问题讨论】:

  • 描述您的例外情况
  • 您不能使用这样的表单,如果您多次添加,您将有重复的字段。它也将映射到模型上的相同字段。您是否为创建的每个局部视图使用唯一的模型?您需要使所有字段 ID 和模型映射都是唯一的

标签: asp.net-mvc asp.net-mvc-4 razor asp.net-ajax


【解决方案1】:

我必须同意 Sandip 在这里的回答,但要详细说明..

@using (Html.BeginForm("AddComment", "Home")) 
{
        //Content to send to the server-side
}

只要您的模型在局部视图中指向您的“评论”对象,那么在使用@Html.EditorFor() 时应该可以正常工作。在您的控制器中,您已经在等待填充“评论”对象。所以在 Post 上,当点击提交时,它将填充该对象。

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    @using (Html.BeginForm("AddComment", "Home")) {

    }

    【讨论】:

    • 尝试使用 Ajax.BeginForm()。它将为您的网站提供性能。
    猜你喜欢
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-20
    相关资源
    最近更新 更多