在模型中使用远程安全验证

第一步:定义Action

        [HttpGet] //必须get,必须json

        public ActionResult CheckItemCodeExists(string ItemCode)  //注意参数名称与前端的元素ID(属性名同名)

        {

            string[] itemCodes = { "bmw-x5", "audi-q7"};

            bool isValid = string.IsNullOrEmpty(itemCodes.FirstOrDefault(x => x == ItemCode));

            return Json(isValid, JsonRequestBehavior.AllowGet); //必须get,必须json

        }

第二步:定义Model

    public class ItemModel

    {

        [DisplayName("物料代码")]

        [Required(ErrorMessage = "[物料代码]不能为空")]

        [Remote("CheckItemCodeExists", "Test", ErrorMessage = "[物料代码]已存在")]

        public string ItemCode { get; set; }

    }

第三步:

@model  MvcApplication3.Models.ItemModel



@section header1 { 

    <script src="@Url.Content("~/Scripts/jquery-1.8.2.min.js")" type="text/javascript"></script>

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

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

}



@{

    ViewBag.Title = "Index";

}



<h2>添加用户</h2>

<fieldset>

    <legend>添加用户</legend>

    <div>

        @using(Html.BeginForm("index","Test")){

        <p>

            @Html.ValidationSummary(true)



            @Html.LabelFor(m=>m.ItemCode):

            @Html.TextBoxFor(m=>m.ItemCode)

            @Html.ValidationMessageFor(m=>m.ItemCode)

        </p>

        <p>

            <input type="submit" value="提 交" />

        </p>

        }

    </div>

</fieldset>

 

你可能感兴趣的:(安全)