When use IEnumerable in view client side validation is not working?

穿精又带淫゛_ 提交于 2019-12-25 05:10:06

问题


I am passing List from Model to view , so I specified in view like this IEnumerable. In this situation Client side validation is not firing

View :

@model  IEnumerable<ShoppingCart.Models.ShoppingClass>
@{
    ViewBag.Title = "Display";

}
<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>

@Html.ValidationSummary(true)
@using (Html.BeginForm())
{

    <table>
        <tr>
            <td>@Html.Label("BrandName")
            </td>
            <td>@Html.TextBox("BrandName")
                <div>
                    @Html.ValidationMessage("BrandName")</div>
            </td>
            <td>
                <input type="submit" value="Search" name="Search" />
            </td>
        </tr>
    </table>

}

回答1:


What you've written is wrong.

You're got the view strongly typed but then you're not using the strongly typed properties or validation messages. Also, you've got the validation summary outside the form.. which won't work.

@using (Html.BeginForm())
@Html.ValidationSummary(true)

Then, you'll need to do something like this:

<table>
    @foreach (ShoppingClass shoppingClass in Model) {
    <tr>
        <td>@Html.LabelFor(x => x.BrandName)
        </td>
        <td>@Html.TextBoxFor(x => x.BrandName)
            <div>
                @Html.ValidationMessageFor(x => x.BrandName)</div>
        </td>
    </tr>
    }
</table>
<input type="submit" value="Search" name="Search" />

I'm not sure why you have a Search button for every item that goes to the same controller and action.. but I'll leave that for you to figure out.



来源:https://stackoverflow.com/questions/11775602/when-use-ienumerable-in-view-client-side-validation-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!