Cascading Text box not working correctly in MVC4? - c#

Hi I have four fields in my view: CustomerName, ContactPerson, Email, MobileNo
CustomerName and ContactPerson are Cascading Dropdown, and Email and MobileNo are textboxes.
If I select the CustomerName, related ContactPerson will load automatically in ContactPerson dropdown.
If I select the Contactperson the related Email and PhoneNo will load automatically in Email and PhoneNo textbox. This works as expected.
If I select the CustomerName as "KPM Processing Limited" it loads the ContactPerson ("Mr.Martin") in contact person textbox which is related to CustomerName("KPM Processing Limited"), and if I select the contact person name (Mr.Martin) the contact person related email (kpm#example.com) and phone number (123456) will automatically load in Email and PhoneNo textbox.
Now I select another customerName (e.g. "N.S colors") after selecting ("KPM Processing Limited") and select the contact person name related to "N.S Colors" ("MR.Luthar"). Now Mr.Luthar has mail Id but didn't have phone no so the value of phone no will be null, but it shows the output as Email=luthar24#example.com and phone no =123456.
In other words, when a contact with null phone number is selected, the displayed phone number doesn't become blank as it should.
My Controller Code:
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);
}
View Code:
#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 Code
<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);
}
});
});
How can I make the phone field blank when the phone number is null?

If I understand correctly, your problem is when change to a customer who has no phone no, the
MobileNo read only textbox value will not clear.
If my understanding is correct, then your problem lies in your Action GetPhoneNoByContactPersonID()
specificaly, when you are getting mobile1 - the linq query you used was FirstOrDefault().Mobile1,
if it can not be find, null will be returned, and calling Mobile1 in null will result excpetion, resulting nothing pass back from ajax.
hence change your action to something like:
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);
}

Related

Load Dropdownlist value in <select> from controller where value and text are different

Hello everyone im just simply trying to load values in a dropdownlist from a controller if I have both the value and text be the same values it works with the model property. But im trying to have the value be the id and the text to be the name with this setup the dropdown is not loading the id.
If both text and value are the same I can just do this and it works
vm.CustomerName = model.CustomerName;
View DDL
#Html.DropDownListFor(e => e.ServiceVM.Employee, Model.Employees, "Select Employee", new { #class = "form-control" })
Some of what i tried.
vm.Employee = new SelectListItem { Value = model.EmployeeID.ToString(), Selected=true };
//vm.EmployeeName = model.EmployeeID.ToString();
//var employee = new Employee_Main();
//try
//{
// employee = context.Employee_Main.Where(z => z.EmployeeID == model.EmployeeID).FirstOrDefault();
//}
//catch(System.Exception) { }
//vm.EmpID = employee.EmployeeID.ToString();
//vm.EmployeeName = employee.EmployeeID.ToString();
I really thought this would of worked.. Im setting the correct 'value' and 'text' that are displayed in the list of ddl items. and also saying selected=true.
//vm.EID = model.EmployeeID;
if (model.EmployeeID != null)
{
if(Int32.TryParse(model.EmployeeID.ToString(), out int empID))
{
var employee = context.Employee_Main.Where(e => e.EmployeeID == empID).FirstOrDefault();
if(employee != null)
{
vm.Employee = new SelectListItem() { Value = employee.EmployeeID.ToString(), Text = employee.EFullName, Selected=true };
}
}
#Html.DropDownListFor(e => e.ServiceVM.Employee, Model.Employees, "Select Employee", new { #class = "form-control" })
I got it working.
I forgot to change my javascript to match with the changing model fields.
var employ = modalA.find(body).find("#ServiceVM_Employee");
//empid.val(jsonObject.employeeid);
//empfn.val(jsonObject.employeefname);
//empln.val(jsonObject.employeelname);
//empem.val(jsonObject.employeeemail);
//emppo.val(jsonObject.employeeposition);
//empname.val(jsonObject.employeefullname);
employ.val(jsonObject.employeeid);
Also for adding content to a listbox.
function displayContactData(conID, modal) {
return $.ajax({
url: '#Url.Action("GetContactInfo", "Service")',
data: { contact: conID },
dataType: 'json',
success: function (data) {
var modalX = modal;
var fullL = modalX.find('.modal-body').find('#lstContact');
fullL.empty();
$.each(data, function () {
fullL.append("<option value='" + this.Value + "'>" + this.Text + "</option");
});
}
});
}

How To Set Value To Drop-down list

I am using jQuery to set the second dropdown list items on selection of the first dropdown. At the time of edit action I want to set fetched data to the second dropdown list. I want to set ViewBag.UserLinkedList to the second dropdown list.
View:
<div class="form-row">
<div class="col-lg-7">
#Html.Label("User Type") #Html.DropDownListFor(m => m.LoginUserTypeID(SelectList)ViewBag.LoginUserTypeList, "--- Select User Type ---", new { #class = "form-control" })
</div>
</div>
<div class="form-row">
<div class="col-lg-7">
#Html.Label("Parent User") #Html.DropDownListFor(m => m.UserLinkedID, new SelectList(""), "--- Select ---", new { #class = "form-control" })
</div>
<script>
$(document).ready(function() {
$("#LoginUserTypeID").change(function() {
$.get("/User/GetParentUserList", {
UserTypeID: $("#LoginUserTypeID").val()
}, function(data) {
$("#UserLinkedID").empty();
$.each(data, function(index, row) {
$("#UserLinkedID").append("<option value='" + row.Id + "'>" + row.Name + "</option>")
});
});
})
});
</script>
Controller:
public JsonResult GetParentUserList(int UserTypeID)
{
List<V_Dealer_DealerEmployee> LinkedIDList = new List<V_Dealer_DealerEmployee>();
if (UserTypeID == 1 || UserTypeID == 2)
{
var d = from s in db.VDNSEmployeeMaster
select new
{
Id = s.EmpId,
Name = s.FirstName + " " + s.MiddleName + " " + s.LastName
};
d.ToList();
return Json(d.ToList(), JsonRequestBehavior.AllowGet);
}
else
{
var unionAll = (from word in db.VDNSDealer select new
{
Id = word.m_code,
Name = word.institute_name
}).Concat(from word in db.DealerEngineerMaster select new {
Id = word.EnggId,
Name = word.EngineerName
});
return Json(unionAll.ToList(), JsonRequestBehavior.AllowGet);
}
}
Edit Action
public ActionResult Edit(int id)
{
var user = db.Users.SingleOrDefault(c => c.Id == id);
if (user == null)
return HttpNotFound();
List<LoginUserType> LoginUserTypeList = db.LoginUserType.ToList();
ViewBag.LoginUserTypeList = new SelectList(LoginUserTypeList, "UserTypeId", "UserTypeName");
List<V_Dealer_DealerEmployee> UserLinkedList = db.VDealerDealerEmployee.ToList();
ViewBag.UserLinkedList = new SelectList(UserLinkedList, "Id", "Name");
return View("New", user);
}
After returning view from edit action, you need to call your change function of LoginUserTypeID. Here is the required js for you
function UpdateUserLinkedIdDropdown(){
var userTypeId = $("#LoginUserTypeID").val();
//This check is for no options selected in LoginUserTypeID Dropdown
if(userTypeId === null || userTypeId === "" || userTypeId === undefined)
userTypeId = 0;
$.get("/User/GetParentUserList", {
UserTypeID: userTypeId
}, function(data) {
$("#UserLinkedID").empty();
$.each(data, function(index, row) {
$("#UserLinkedID").append("<option value='" + row.Id + "'>" + row.Name + "</option>")
});
});
}
$("#LoginUserTypeID").change(function() {
UpdateUserLinkedIdDropdown();
});
// Call it initially when view loaded
// You can do it in this way
UpdateUserLinkedIdDropdown();
// OR This way
$("#LoginUserTypeID").trigger('change');
Give it a try! I think this will work. If not comment plz

search mvc json jquery

I'm having trouble with auto-search when I want to make two values
I want to search the store for product, please guide:
Controller
public JsonResult Search(string pr, string name, string model, string brand, string storename) {
var s = _context.Products.Where(a => a.Name.Contains(pr) || a.Model.Contains(pr) || a.Brands.Name.Contains(pr)).Select(a => new {
name = a.Name, model = a.Model, brand = a.Brands.Name
}).Take(10);
var storen = _context.Stores.Where(a => a.Name.StartsWith(pr)).Select(a => new {
storename = a.Name
});
return Json(new {
s,
storen
}, JsonRequestBehavior.AllowGet);
}
View
$(document).ready(function () {
var kam;
$("#CityName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/search",
type: "POST",
dataType: "json",
data: {
pr: request.term
},
success: function (data) {
response($.map(data, function (item) {
return [{
label: item.name + " " + item.model + " " + item.brand,
value: item.name + " " + item.model + " " + item.brand
}]
}))
}
})
},
messages: {
noResults: "",
results: ""
}
});
})
I think you want to combine both result sets to show into one Autocomplete widget. So for that, try to modify your code to look like this
Controller
public JsonResult Search(string pr) {
var s = _context.Products.Where(a => a.Name.Contains(pr) || a.Model.Contains(pr) || a.Brands.Name.Contains(pr)).Take(10).Select(a => new {
resultItem = a.Name + " " + a.Model + " " + a.Brands.Name
}).ToList();
var storen = _context.Stores.Where(a => a.Name.StartsWith(pr)).Select(a => new {
resultItem = a.Name
}).ToList();
var returnList = s.Concat(storen).ToList();
return Json(new {
returnList
}, JsonRequestBehavior.AllowGet);
}
This way your controller returns only one result set in json format.
View
$(document).ready(function () {
$("#CityName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/Search",
type: "GET",
dataType: "json",
data: {
pr: request.term
},
success: function (data) {
response($.map(data, function (item) {
return [{
label: item.resultItem,
value: item.resultItem
}]
}))
}
})
},
messages: {
noResults: "",
results: ""
}
});
})
Note that I have changed the ajax request type to GET and label and value use the same resultItem field.
Instaed of:
var storen = _context
.Stores
.Where(a => a.Name.StartsWith(pr))
.Select(a => new { storename = a.Name });
Don't you want to use Contains, like in the first query ?
var storen = _context
.Stores
.Where(a => a.Name.Contains(pr))
.Select(a => new { storename = a.Name });

TextBox to Auto-Fill

If a user is typing something into a textbox on a form, and what they are typing in starts to match a value that is already in the database, how do I get the textbox to give the option to auto-fill the rest of what the user wants to type in based on the value that is already in the database?
Consider I have this table(name of table: Person) in my database:
|ID| |FirstName| |LastName|
1 John Smith
2 Tom Jones
3 James Davis
and on the form where the user wants to create a new Person they start to type in jo into the FirstName textbox.. how do i get the textbox to give the option to autofill the hn and capitalize the first letter to spell John?
Any help is appreciated.
UPDATE:
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Create([Bind(Include = "ID,text,subcategory")] Activity codeAC, string term)
{
if (ModelState.IsValid)
{
var result = (from r in db.Activities
where r.subcategory.ToUpper().Contains(term.ToUpper())
select new { r.subcategory }).Distinct();
db.Activities.Add(codeAC);
db.SaveChanges();
return Json(result, JsonRequestBehavior.AllowGet);
}
return Json(codeAC);
}
Script:
<script type="text/javascript">
$(document).ready(function () {
$('#Categories').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Activities/Create",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.subcategory, value: item.subcategory };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
CSHTML:
<div class="form-group">
#Html.LabelFor(model => model.subcategory, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.subcategory, new { htmlAttributes = new { #id = "Categories", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.subcategory, "", new { #class = "text-danger" })
</div>
</div>
I figured it out. I didn't know that I couldn't incorporate this into my Create ActionResult.. so I created a separate JsonResult method and it is working.
Controller:
public JsonResult AutoCompleteCategory(string term)
{
var result = (from r in db.Activities
where r.subcategory.ToUpper().Contains(term.ToUpper())
select new { r.subcategory }).Distinct();
return Json(result, JsonRequestBehavior.AllowGet);
}
SCRIPT:
<script type="text/javascript">
$(document).ready(function () {
$('#Categories').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Activities/AutoCompleteCategory",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.subcategory, value: item.subcategory };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
</script>

Cascading text box is not working correctly in MVC4?

Hi I have four fields in my view CustomerName, ContactPerson, Email, MobileNo
CustomerName and ContactPerson are Cascading Dropdown, and Email and MobileNo are textboxes.
If I select the CustomerName, related ContactPerson will load automatically in ContactPerson dropdown.
If I select the Contactperson the Contact person related Email and PhoneNo will load automatically in Email and PhoneNo textbox. This works as expected.
Now all are working fine the two cascading drop down are working fine now my issue is if i select the contact person the contact person related Email and phone no is not displaying in that appropriate text boxes.
My Controller Code:
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 GetPhoneNoByContactPersonID(Guid CustomerContactId)
{
var resultMobileNumber = string.Empty;
var resultEmail = string.Empty;
var ContactID = db.CustomerContacts.Where(i => i.CustomerContactID == CustomerContactId).Select(i => i.ContactID).FirstOrDefault();
if (ContactID != null)
{
var contact = (from p in db.Contacts where p.ContactID == ContactID select p).FirstOrDefault();
if (contact != null)
{
if (string.IsNullOrEmpty(contact.Mobile1) == false)
{
resultMobileNumber = contact.Mobile1;
}
else if (string.IsNullOrEmpty(contact.Mobile2) == false)
{
resultMobileNumber = contact.Mobile2;
}
}
if (contact != null)
{
if (string.IsNullOrEmpty(contact.Email1) == false)
{
resultEmail = contact.Email1;
}
else if (string.IsNullOrEmpty(contact.Email2) == false)
{
resultEmail = contact.Email2;
}
}
}
var details = new { success = true, email = resultEmail, mobileno = resultMobileNumber };
return Json(details, JsonRequestBehavior.AllowGet);
}
View Code:
#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)
J-query Code
<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");
debugger;
$.ajax(
'#Url.Action("GetPhoneNoByContactPersonID", "VisitorsForm")',{
type: "GET",
dataType: "html",
async: false,
data: { CustomerContactID: $("#CustomerContactID").val()
},
error: function (ex) {
alert('Failed to retrieve Email.' + ex);
},
beforeSend: function () {
},
success: function (data) {
$("#Email").val(data.email);
$("#MobileNo").val(data.mobileno)
alert("Success");
}
});
});
Now all are working fine when i click the contact person it come to the GetPhoneNoByContactPersonID action it calculate the values and return again to the view ans it is also visible in Network too. All are perfect but it not displaying the data in textbox. while i inspect the code it didn't show any error in console. But it shows one warning message which is mentioned below.
Now all are working fine. But i donno why it is not displaying i donno where is the issue is. I tried my level bwst to explain my issue.-please any one help me to clear this issue.
Advance Thanks
There is no id associated with.So assign an id first in TextBoxFor like this.
#Html.TextBoxFor(model => model.MobileNo, new {#id = "MobileNo", #class = "form-control", type = "text",disabled = "disabled", #readonly = "readonly" })
#Html.TextBoxFor(model => model.Email, new {#id = "Email", #class = "form-control", type = "text" ,disabled = "disabled", #readonly = "readonly" })
Now this should work
$("#Email").val(data.email);
$("#MobileNo").val(data.mobileno)

Categories