简体   繁体   English

MVC-模糊事件的远程验证

[英]MVC - Remote validation for the blur event

I am trying to verify that a code entered into the web page is valid by reading a backend database when the text box loses focus. 我试图通过在文本框失去焦点时读取后端数据库来验证输入到网页中的代码是否有效。 I am able to execute the code in the controller but for some reason the model object is not being passed to the controller method. 我能够在控制器中执行代码,但是由于某种原因,模型对象未传递给控制器​​方法。

The text box definition... 文本框定义...

<div class="form-group">
    @Html.LabelFor(m => m.HSDRepCode)
    @Html.TextBoxFor(m => m.HSDRepCode, new { placeholder = "Enter your HSD Rep code...", @class = "contact-name"})
    @Html.ValidationMessageFor(m => m.HSDRepCode)
</div>

The javascript code for the blur event... 模糊事件的JavaScript代码...

<script type="text/javascript">
    $("#HSDRepCode").blur(function () {
        var model = '@Html.Raw(Json.Encode(Model))';

        $.ajax({
            url: "/CRM/ValidateHSDRep",
            type: "POST",
            data: $("model").serialize(),
            dataType: "application/json"
            }).done(function( model ) {
                $("#HSFirstName").val(model.HSFirstName);
                $("#HSLastName").val(model.HSLastName);
                });
        });
    </script>

The CRM controller code... CRM控制器代码...

public ActionResult ValidateHSDRep(LeadInfo leadInfo)
    {
        HSDRep hsdRep = new HSDRep();

        hsdRep = CRMModels.ValidateHSDRepCode(leadInfo.HSDRepCode);

        return Json(leadInfo);
    }

The controller code is executed but the leadInfo object is all nulls after entering the HSDRepCode and tabbing to the next text box. 输入HSDRepCode并跳至下一个文本框后,将执行控制器代码,但leadInfo对象为空。

Why isn't the model being passed to the controller code? 为什么不将模型传递给控制器​​代码?

Thanks, Gary 谢谢,加里

The model variable doesn´t have the serialize() method, this method is just to use with forms elements. 模型变量没有serialize()方法,该方法仅用于表单元素。 Try remove the single quote from this line: var model = @Html.Raw(Json.Encode(Model)); 尝试从此行删除单引号:var model = @ Html.Raw(Json.Encode(Model)); Now send the model object as the data: model. 现在将模型对象作为数据发送:模型。

    <script type="text/javascript">
$("#HSDRepCode").blur(function () {
    var model = @Html.Raw(Json.Encode(Model));

    if(model == null) {
        model = {};
    }

    model.HSDRepCode = $(this).val();

    $.ajax({
        url: "/CRM/ValidateHSDRep",
        type: "POST",
        data: model,
        dataType: "application/json"
    }).done(function (model) {
        $("#HSFirstName").val(model.HSFirstName);
        $("#HSLastName").val(model.HSLastName);
    });
});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM