客户端验证是否有效,但是将Null值传递给MVC3中的控制器?

时间:2012-07-27 09:03:27

标签: asp.net-mvc-3

客户端验证无效...... 同样的过程我在另一个页面上完成了它的工作但没有使用forloop。 在这里,当我键入文本而不进行验证时,只需勾选图像显示...给我解决方案..

查看

 @model IList<clientval.Models.ShoppingClass>
 @using (Html.BeginForm("Login", "Home"))
        {
            for (int i =0; i <1; i++)
            {


        <table>
        <tr>
        <td>@Html.Label("FirstName")</td>
        <td>@Html.TextBox("FirstName")<div>@Html.ValidationMessageFor(o => o[i].FirstName)</div></td>
        <td>@Html.Label("LastName")</td>
        <td>@Html.TextBox("LastName")<div>@Html.ValidationMessageFor(o => o[i].LastName)</div></td>
        <tr>
        }
        }

脚本

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="../../assets/js/ClientScript.js" type="text/javascript"></script>

控制器

[AcceptVerbs(HttpVerbs.Post)]
 public ActionResult Guestlogin(string firstname, string lastname)
        {

              ShoppingClass s = new ShoppingClass();
              var button = Request["button"];
              var ob = s.Newcustomer(customerfirstname, customerlastname);
             TempData["BN"] = ob;
            return RedirectToAction("Sucessfully", ob);

        }

模型是

    [Required(ErrorMessage = "First Name is Required")]
    [RegularExpression(@"^[a-zA-Z ]*$", ErrorMessage = "First Name is Not valid")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Last Name is Required")]
    [RegularExpression(@"^[a-zA-Z ]*$", ErrorMessage = "Last Name is Not valid")]
    public string LastName { get; set; }
    public List<ShoppingClass> Newcustomer(string firstname, string lastname)
        {

            List<ShoppingClass> list = new List<ShoppingClass>();
            ShoppingClass obj = new ShoppingClass();
.
.
.
            }

2 个答案:

答案 0 :(得分:1)

不确定你在使用for循环做了什么,但我猜这只是一个例子?

你不应该像这样使用TextBoxFor和LabelFor:

@using (Html.BeginForm("Login", "Home"))
        {
            for (int i =0; i <1; i++)
            {


        <table>
        <tr>
        <td>@Html.LabelFor(o => o[i].FirstName)</td>
        <td>@Html.TextBoxFor(o => o[i].FirstName)<div>@Html.ValidationMessageFor(o => o[i].FirstName)</div></td>
        <td>@Html.LabelFor(o => o[i].LastName)</td>
        <td>@Html.TextBoxFor(o => o[i].LastName)<div>@Html.ValidationMessageFor(o => o[i].LastName)</div></td>
        <tr>
        }
        }

答案 1 :(得分:0)

试试这个:

Html.Validate("FirstName");

在所有领域都是这样的