【问题标题】:Cascading Text box not working correctly in MVC4?级联文本框在 MVC4 中无法正常工作?
【发布时间】:2016-03-07 13:05:32
【问题描述】:

您好,我的视图中有四个字段:CustomerNameContactPersonEmailMobileNo

CustomerNameContactPerson 是级联下拉菜单,EmailMobileNo 是文本框。

如果我选择CustomerName,相关的ContactPerson 将自动加载到ContactPerson 下拉列表中。

如果我选择Contactperson,相关的EmailPhoneNo 将自动加载到EmailPhoneNo 文本框中。这按预期工作。

如果我选择CustomerName 作为"KPM Processing Limited",它会在与CustomerName("KPM Processing Limited") 相关的联系人文本框中加载ContactPerson ("Mr.Martin"),如果我选择联系人姓名(Mr.Martin)联系人相关的电子邮件 (kpm@example.com) 和电话号码 (123456) 将自动加载到电子邮件和电话号码文本框中。

现在我在选择("KPM Processing Limited")后选择另一个customerName(例如"N.S colors")并选择与“N.S Colors”相关的联系人姓名("MR.Luthar")。现在 Mr.Luthar 有邮件 ID 但没有电话号码,所以电话号码的值为空,但它显示输出为 Email=luthar24@example.com 和电话号码 =123456

In other words, when a contact with null phone number is selected, the displayed phone number doesn't become blank as it should.

我的控制器代码:

  public JsonResult GetCustomers()
 {
    return Json(db.Customers.ToList(), JsonRequestBehavior.AllowGet);
 }

    public JsonResult GetContactPersobByCustomerId(string customerId)
   {
    Guid Id = Guid.Parse(customerId);
    var customercontacts = (from a in db.CustomerContacts where a.CustomerID == Id select a);
    return Json(customercontacts, JsonRequestBehavior.AllowGet);
   } 

    public JsonResult GetEmailByContactPersonID(Guid CustomerContactId)
   {
  var ContactID = db.CustomerContacts.Where(i => i.CustomerContactID == CustomerContactId).Select(i => i.ContactID).FirstOrDefault();
  var contact1 = (from p in db.Contacts where p.ContactID == ContactID select p).FirstOrDefault().Email1;
    if (contact1 == null)
    {
        var contact2 = (from a in db.Contacts where a.ContactID == ContactID select a).FirstOrDefault().Email2;
        contact1 = contact2;
    }
    return Json(contact1, JsonRequestBehavior.AllowGet);
 }

  public JsonResult GetPhoneNoByContactPersonID(Guid CustomerContactId)
{
    var ContactID = db.CustomerContacts.Where(i => i.CustomerContactID == CustomerContactId).Select(i => i.ContactID).FirstOrDefault();
    var mobile1 = (from pn in db.Contacts where pn.ContactID == ContactID select pn).FirstOrDefault().Mobile1;
    if (mobile1 == null)
    {
        var mobile2 = (from a in db.Contacts where a.ContactID == ContactID select a).FirstOrDefault().Mobile2;

        mobile1 = mobile2;
    }
    return Json( mobile1, JsonRequestBehavior.AllowGet);
}

查看代码:

 @Html.Label("Customer Name", new { @class = "control-label" })
 @Html.DropDownListFor(model => model.CustomerID, new SelectList(string.Empty, "Value", "Text"), "Please select a Customer", new {     @class = "form-control required", type = "text" })

 @Html.Label("Contact Person", new { @class = "control-label" })
 @Html.DropDownListFor(model => model.CustomerContactID, new SelectList(string.Empty, "Value", "Text"), "Please select a ContactPerson", new { @class = "form-control", type = "text", id = "CustomerContactID" })

 @Html.LabelFor(model => model.MobileNo, new { @class = "control-label" })
 @Html.TextBoxFor(model => model.MobileNo, new { @class = "form-control", type = "text",disabled = "disabled", @readonly = "readonly"  })
 @Html.ValidationMessageFor(model => model.MobileNo)

 @Html.LabelFor(model => model.Email, new { @class = "control-label" })
 @Html.TextBoxFor(model => model.Email, new { @class = "form-control", type = "text" ,disabled = "disabled", @readonly = "readonly" })
 @Html.ValidationMessageFor(model => model.Email)

jQuery 代码

 <script src="~/Scripts/jquery-ui-1.11.0.js"></script>
  <script>
  $(function () {
  $.ajax(
    '@Url.Action("GetCustomers", "VisitorsForm")',{
        type: "GET",
        datatype: "Json",
        success: function (data) {
            $.each(data, function (index, value) {
                $('#CustomerID').append('<option value="' + value.CustomerID + '">' + value.DisplayName + '</option>');
            });
        }
    });

  $('#CustomerID').change(function () {
   $('#CustomerContactID').empty();
    $.ajax(
       '@Url.Action("GetContactPersobByCustomerId", "VisitorsForm")',{
            type: "POST",
            datatype: "Json",
            data: { CustomerID: $('#CustomerID').val() },
            success: function (data) {
        $('#CustomerContactID').append($('<option></option>').val('').text('Please select'));
                $.each(data, function (index, value) {
             $('#CustomerContactID').append('<option value="' + value.CustomerContactID + '">' + value.ContactReference + '</option>');
               });
              }
           });
        });
    });

   $("#CustomerContactID").change(function () {
       alert("hhh");
    $.ajax(
    '@Url.Action("GetEmailByContactPersonID", "VisitorsForm")',{
        type: "GET",
        dataType: "json",
        async: false,
        data: { CustomerContactID: $("#CustomerContactID").val()
        },
        error: function (ex) {
            alert('Failed to retrieve Email.' + ex);
        },
        beforeSend: function () {
        },
        success: function (data) {
            $("#Email").val(data);
                         }
                     });
                 });

  $("#CustomerContactID").change(function () {
   alert("hhh");
  $.ajax(
    '@Url.Action("GetPhoneNoByContactPersonID", "VisitorsForm")',{
        type: "GET",
        dataType: "json",
        async: false,
        data: { CustomerContactID: $("#CustomerContactID").val()
        },
        error: function (ex) {
            alert('Failed to retrieve Email.' + ex);
        },
        beforeSend: function () {
        },
        success: function (data) {

            $("#MobileNo").val(data);
        }
      });
    });

电话号码为空时如何让电话字段为空?

【问题讨论】:

  • 根据您的最后一个问题,不要对 2 个单独的方法进行 2 个单独的 ajax 调用。对一种方法进行一次调用,该方法返回一个包含两个值的匿名对象。而你的控制器正在抛出异常,这就是为什么值不会被更新。

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


【解决方案1】:

如果我理解正确,您的问题是当更改为没有电话号码的客户时, MobileNo 只读文本框的值不会被清除。

如果我的理解是正确的,那么你的问题在于你的 Action GetPhoneNoByContactPersonID()

具体来说,当您获得 mobile1 - 您使用的 linq 查询是 FirstOrDefault().Mobile1, 如果找不到,则返回null,在null中调用Mobile1将导致异常,导致ajax没有返回任何内容。

因此将您的操作更改为:

public JsonResult GetPhoneNoByContactPersonID(Guid CustomerContactId)
{
    var resultMobileNumber = string.Empty;

    var ContactID = db.CustomerContacts.Where(i => i.CustomerContactID == CustomerContactId).Select(i => i.ContactID).FirstOrDefault();
    if(ContactID != null)
    {
    var contact = (from pn in db.Contacts where pn.ContactID == ContactID select pn).FirstOrDefault();
    // check if contact is found
        if (contact != null)
    {
        // if mobile 1 has value
        if(string.IsNullOrEmpty(contact.Mobile1) == false)
        {
            resultMobileNumber  = contact.Mobile1;
        }
        else if(string.IsNullOrEmpty(contact.Mobile2) == false)
        {
            resultMobileNumber  = contact.Mobile2;
        }
    }
    }

    return Json(resultMobileNumber, JsonRequestBehavior.AllowGet);
}

【讨论】:

    猜你喜欢
    • 2012-05-16
    • 1970-01-01
    • 2013-03-11
    • 1970-01-01
    • 2013-10-26
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多