代码之家  ›  专栏  ›  技术社区  ›  H4mm3rHead

ASP.NET MVC表单的简单验证失败

  •  0
  • H4mm3rHead  · 技术社区  · 15 年前

    <%=Html.ValidationSummary() %>
        <table>
            <tr>
                <td>
                    Feed Url:
                </td>
                <td>
                    <%=Html.TextBox("url", null, new {@style="width:300px"}) %>
                </td>
            </tr></table>
    

    我的控制器也很简单:

    [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AddFeed(FormCollection collection)
        {
            string url = collection.Get("url");
            string roles = collection.Get("Roles");
            if (string.IsNullOrEmpty(url))
            {
                ModelState.AddModelError("url", "Please provide a propre feed url");
            }
            if (string.IsNullOrEmpty(roles))
            {
                ModelState.AddModelError("Roles", "Please select a valid role");
            }
            if (ModelState.IsValid)
            {
                Session["url"] = url;
                Session["Roles"] = roles;
                return RedirectToAction("ValidateFeed");
            }
            else
            {
                return View();
            }
        }
    

    /H4mm3r型

    请忽略Roles元素,我有一个下拉列表,但为了简单起见从标记中删除了它

    2 回复  |  直到 15 年前
        1
  •  0
  •   Jay Querido    15 年前

    在使用HTML助手时,可能不能使用null。改为在表单中尝试此操作:

    <%= Html.TextBox("url", String.Empty, new {@style="width:300px"}) %>
    

    我还没有测试过,但考虑到错误信息,这是我第一次尝试。

        2
  •  0
  •   JOBG    15 年前

    UpdateModel(collection);
    

    TryUpdateModel(collection);
    

    public ActionResult AddFeed(YourModelType collection)
    

    因为Modelstate与任何模型都没有关联。

    正如MSDN参考资料所说:

    模型状态类

    封装模型的状态 操作方法参数,或 争论本身。