如何根据另一个字段的值自动填充其他字段

时间:2018-09-07 00:41:17

标签: c# jquery ajax asp.net-mvc

这是我的ajax / jquery代码,它将电话字段的值发送给控制器

<script type="text/javascript">
    debugger;
    $(document).ready(function () {
        //Dropdownlist Selectedchange event
        $("#button").click(function () {
            debugger;
            alert("phonechanged");

            $.ajax({
                type: "POST",
                dataType: 'json',
                contentType: 'application/json',
                url: '@Url.Action("CheckPhone")',
                //data: { phone: $("#phone").val() },
                data: JSON.stringify({ phone: $("#phone").val() }),
                success: function (data) {
                    debugger;
                    var obj = JSON.parse(data);
                    $("#firstName").val(obj.firstName);

                },
                error: function (ex) {
                    debugger;
                    alert('Failed to retrieve customer.' + ex);
                }
            });

            return false;
        })
    });
</script>   

这是我的控制器方法,应该返回客户(如果有),然后让ajax更改field的值。我的代码无法正常工作。如果没有客户拥有该电话号码,我也不知道如何检查空值。

[HttpPost]
public JsonResult CheckPhone(string phone)
{
    Customer cm = new Customer();
    bool check = false;
    Leads_Management_SystemEntities lmsEntities = new Leads_Management_SystemEntities();
    cm = lmsEntities.Customers.FirstOrDefault(x => x.phoneNum1 == phone || x.phoneNum2 == phone || x.phoneNum3 == phone);


    string value = string.Empty;
    value = JsonConvert.SerializeObject(cm, Formatting.Indented, new JsonSerializerSettings
    {
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
    });

    return Json(value);
}

剃刀代码

<div class="form-group">
            @Html.LabelFor(model => model.firstName, new { @class = "control-label col-md-2"})
            <div class="col-md-10">
                @Html.EditorFor(model => model.firstName, new { id = "firstName" })
                @Html.ValidationMessageFor(model => model.firstName)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.email, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.email)
                @Html.ValidationMessageFor(model => model.email)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.city, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.city)
                @Html.ValidationMessageFor(model => model.city)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.country, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.country)
                @Html.ValidationMessageFor(model => model.country)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.phoneNum1, new { @class = "control-label col-md-2"})
            <div class="col-md-10">
                @Html.EditorFor(model => model.phoneNum1, new { id = "phone" })
                @Html.ValidationMessageFor(model => model.phoneNum1)
            </div>
        </div>

            <input type="submit" value="submit" id="button" />


        <div class="form-group">
            @Html.LabelFor(model => model.phoneNum2, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.phoneNum2)
                @Html.ValidationMessageFor(model => model.phoneNum2)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.phoneNum3, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.phoneNum3)
                @Html.ValidationMessageFor(model => model.phoneNum3)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.propertyOwned, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.propertyOwned)
                @Html.ValidationMessageFor(model => model.propertyOwned)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.address, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.address)
                @Html.ValidationMessageFor(model => model.address)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.CNIC, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.CNIC)
                @Html.ValidationMessageFor(model => model.CNIC)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.lastName, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.lastName)
                @Html.ValidationMessageFor(model => model.lastName)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.budgetTo, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.budgetTo)
                @Html.ValidationMessageFor(model => model.budgetTo)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.budgetFrom, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.budgetFrom)
                @Html.ValidationMessageFor(model => model.budgetFrom)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.leadScoreId, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.leadScoreId, (IEnumerable<SelectListItem>)ViewBag.lsList, "Select leadscore")
                @*@Html.EditorFor(model => model.leadScoreId)*@
                @Html.ValidationMessageFor(model => model.leadScoreId)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.plotSize, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.plotSize)
                @Html.ValidationMessageFor(model => model.plotSize)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.statusId, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.statusId, (IEnumerable<SelectListItem>)ViewBag.statusList, "Select status")
                @*@Html.EditorFor(model => model.statusId)*@
                @Html.ValidationMessageFor(model => model.statusId)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.uniqueHandle, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.uniqueHandle)
                @Html.ValidationMessageFor(model => model.uniqueHandle)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.plotTypeId, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.plotTypeId, (IEnumerable<SelectListItem>)ViewBag.ptList, "Select plotType")



                @*@Html.EditorFor(model => model.plotTypeId)*@
                @Html.ValidationMessageFor(model => model.plotTypeId)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Block, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Block)
                @Html.ValidationMessageFor(model => model.Block)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.commentsDetails, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.commentsDetails)
                @Html.ValidationMessageFor(model => model.commentsDetails)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.typeId, new { @class = "control-label col-md-2" })
            <div class="col-md-10">

                @Html.DropDownListFor(model => model.typeId, (IEnumerable<SelectListItem>)ViewBag.stList, "Select sourcetype")
                @*@Html.EditorFor(model => model.typeId)*@
                @Html.ValidationMessageFor(model => model.typeId)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.sourceTime, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.sourceTime)
                @Html.ValidationMessageFor(model => model.sourceTime)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.commentsSource, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.commentsSource)
                @Html.ValidationMessageFor(model => model.commentsSource)
            </div>
        </div>
@*this form group wasnot auto generated*@
        <div class="form-group">
            @Html.LabelFor(model => model.tags, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.ListBoxFor(model => model.tags, (MultiSelectList)(ViewData["tags"]) as SelectList)
                @*@Html.EditorFor(model => model.tags)*@
                @Html.ValidationMessageFor(model => model.tags)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.features, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.ListBoxFor(model => model.features, (MultiSelectList)(ViewData["features"]) as SelectList)
                @*@Html.EditorFor(model => model.features)*@
                @Html.ValidationMessageFor(model => model.features)
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

1 个答案:

答案 0 :(得分:-1)

代码有两个问题。让我们从动作开始:

  • lmsEntities未被处置
  • 未使用的变量被声明
  • (通过延迟加载)从数据库中选择了比所需更多的数据
  • cm被序列化两次-一个通过JsonConvert.SerializeObject,另一个通过Json。这会在AJAX成功事件中强制进行不必要的JSON.parse调用。

总体来说,它看起来应该像这样:

[HttpPost]
public JsonResult CheckPhone(string phone)
{
    using (var lmsEntities = new Leads_Management_SystemEntities())
    {
        var customer = lmsEntities.Customers
            .Where(x => x.phoneNum1 == phone || x.phoneNum2 == phone || x.phoneNum3 == phone)
            .Select(x => new 
            {
                // select whatever needed
                x.firstName,
                x.LastName
            })
            .FirstOrDefault();

        return Json(customer);
    }
}

然后,AJAX正常运行所需的唯一更新如下:

$.ajax({
    type: "POST",
    dataType: 'json',
    contentType: 'application/json',
    url: '@Url.Action("CheckPhone")',
    //data: { phone: $("#phone").val() },
    data: $("#phone").val(),
    success: function (data) {
        debugger;

        //if nothing was retrieved from the server
        if (!data)
        {
            return;
        }

        // no need for the JSON.parse call, use data directly
        $("#firstName").val(data.firstName);

    },
    error: function (ex) {
        debugger;
        alert('Failed to retrieve customer.' + ex);
    }
});