【问题标题】:Simple way to disable model validation for disabled form input?禁用表单输入的模型验证的简单方法?
【发布时间】:2017-06-18 02:34:16
【问题描述】:

是否有一种简单的方法可以在禁用的输入字段上禁用模型验证?我的问题是我有一个带有模型验证的表单我正在使用 jquery 禁用输入并隐藏它并使用 Ajax 提交表单但是当它被禁用时它仍然对该字段进行模型验证我正在为客户端使用 html 5 验证服务器端的端和模型验证。任何帮助将不胜感激。这只是我代码的一部分,它要大得多,但我只是想知道是否有一种简单的方法可以在禁用的输入字段上禁用模型验证。不确定您是否能够说出它如何与我的代码示例一起使用,我试图简化它们以理解这一点,但我想我可能已经扼杀了它。我从位置文本框中删除所需的 html 5 并禁用以测试模型验证效果很好,但我不希望它在禁用位置文本框时工作。

部分模型

   [Required(ErrorMessage = "You must enter a location")]
    [StringLength(15, ErrorMessage ="Must Be Under 15 Characters")]
    public string location_txt_box { get; set; }

控制器部分

[HttpPost]
    [ValidateAjax]
    public JsonResult AddData(form_model form_data)
    {
        return Json(form_data);
    }

    public class ValidateAjaxAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!filterContext.HttpContext.Request.IsAjaxRequest())
                return;

            var modelState = filterContext.Controller.ViewData.ModelState;
            if (!modelState.IsValid)
            {
                var errorModel =
                        from x in modelState.Keys
                        where modelState[x].Errors.Count > 0 select new
                        {
                            key = x,
                            errors = modelState[x].Errors.Select(y => y.ErrorMessage).ToArray()
                        };
                filterContext.Result = new JsonResult()
                {
                    Data = errorModel
                };
                filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
            }
        }
    }

部分视图

<section class="u_select_section">
                    <center>
                        <label>
       @Html.RadioButtonFor(m => m.user_department_radio_group,"user", htmlAttributes: new{
                            @id = "u_select"
                            })
                            Filling out for myself
                        </label>

                    </center>
                </section>

                <section id="location_display_section" class="location_display_section">

                   <div id="location_error"></div>
                    @Html.TextBoxFor(m => m.location_txt_box, htmlAttributes: new{

                   @id = "dep_loca_id",
                   @disabled = "disabled",
                   @placeholder = "Type your Location",
                   @required = "required" 
               })

                </section>

jquery 的一部分

$('#request_form').on('submit', function (e) {

            $.ajax({
                type: "POST",
                url: "../Home/AddData",
                datatype: "json",
                data: $("#request_form").serializeArray(),

                beforeSend: function () {
                    $("#progress").show();
                },
                complete: function () {
                    $('#progress').hide("fade",2000);
                },
                success: function (data) {

                    alert("Success")

                },
                error: function (data) {

                    $("#location_error").show();
                    var response = JSON.parse(data.responseText);
                    var location_error = response[0].errors[0];
                    $("#location_error").text("" + location_error + "").css({ "color": "red" });

                }

            });

        e.preventDefault();
    });

用于隐藏和禁用的 Jquery

//disable functions
    function disable_function_1(i) {
        return $(i).attr("disabled", "disabled");
    }  

    //user and department radio button click functions
    $("#u_select").click(function () {


       $(dep_loca_id).hide(effect1);//hide the department location text box
        disable_function_1(dep_loca_id);//disable the department location text box

    });

【问题讨论】:

  • 发布一些示例代码

标签: jquery asp.net-mvc


【解决方案1】:

您可以使用ModelState.Remove() 删除特定字段验证。

[HttpPost]
public ActionResult YourAction(YourModel model)  
{
    // your condition here
    ModelState.Remove("location_txt_box "); // to omit specific field according to condition

    if (ModelState.IsValid)
    {
      // your code here
    }   

    return View();
}

【讨论】:

  • 这可能只需要弄清楚文本框是否因条件而被禁用只是不确定我是否可以检查这对 mvc 和 c# 来说还是有点新的我会试一试跨度>
  • 什么时候禁用文本框输入?
  • 是否能够了解您的用户和部门单选按钮是否被您的模型所点击?
  • 在我的模型中,我将它们设置为单选按钮的字符串,起初我将它们设置为布尔值,但我没有从它们那里得到我想要的。当我放置一个断点以查看模型的用户或部门取决于选择了哪个模型时,我得到了值当用户选择用户单选按钮时禁用文本框
  • 因此您可以通过在 ModelState.Remove() 之前检查模型来添加条件
猜你喜欢
  • 2021-03-06
  • 1970-01-01
  • 1970-01-01
  • 2018-11-21
  • 2011-03-25
  • 2017-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多