Autocomplete dropdown in MVC5? - c#

Hi i have one field in my view. That field is Customer it is a dropdown field. In that i have keep dropdown as select option to select the value. But i like to change that field as Autocomplete dropdown.
In the above image I have customerName field as dropdown field but i keep it by search and select option. But now i like to change this to autocomplete dropdown like which is mention the in the below image.
My 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" })
My jquery Code
$(function () {
debugger;
$.ajax(
'#Url.Action("GetVisitCustomer", "VisitorsForm", new { Area = "Sales" })',{
type: "GET",
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#CustomerID').append('<option value="' + value.CustomerID + '">' + value.DisplayName + '</option>');
});
}
});
});
My Controller Code to get Customers and load in the field
public JsonResult GetVisitCustomer()
{
var objCustomerlist = (from c in db.Customers where c.IsDeleted== false select c).ToList();
return Json( objCustomerlist,JsonRequestBehavior.AllowGet);
}
I tried to explain my issue. Any one help to resolve this issue. I tried many ways but its not working. So any one understand my issue and give some solution or suggesstions.
The Code which i have tried
My View Code
#Html.Label("Customer Name", new { #class = "control-label" })
#Html.TextBoxFor(Model=>Model.CustomerID)
My Jquery Code
<script type="text/javascript">
$(document).ready(function () {
debugger;
$("#CustomerID").autocomplete({
source: function (request, response) {
$.ajax(
'#Url.Action("GetVisitCustomer", "VisitorsForm", new { Area = "Sales" })', {
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return
{ label=item.CustomerID, value= item.DisplayName
};
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
</script>
But this code is not working
Advance Thanks..

Kindly see code below:
HTML
#Html.LabelFor(model => Model.CustomerName, new { #class = "control-label" })
#Html.TextBoxFor(model => Model.CustomerName, new { #class = "form-control"})
#Html.HiddenFor(model => Model.CustomerID)
JS
$(document).ready(function () {
$("#CustomerName").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetVisitCustomer", "Home")',
datatype: "json",
data: {
Areas: 'Sales',
term: request.term
},
success: function (data) {
response($.map(data, function (val, item) {
return {
label: val.Name,
value: val.Name,
customerId: val.ID
}
}))
}
})
},
select: function (event, ui) {
$("#CustomerID").val(ui.item.customerId);
}
});
});
CODE
public JsonResult GetVisitCustomer(string Areas, string term = "")
{
var objCustomerlist = db.Customers.Where(c => c.IsDeleted == false)
.Where(c => c.CustomerName.ToUpper()
.Contains(term.ToUpper()))
.Select(c => new { Name = c.CustomerName, ID = c.CustomerID })
.Distinct().ToList();
return Json(objCustomerlist, JsonRequestBehavior.AllowGet);
}
Sample screenshot

Related

Cascading (Dependent) Country State City DropDownLists using jQuery AJAX in ASP.Net MVC

I need to populate Cascading Country, State and City DropDownLists using jQuery AJAX in ASP.Net MVC.
This is the tutorial
https://www.aspsnippets.com/Articles/Cascading-Dependent-Country-State-City-DropDownLists-using-jQuery-AJAX-in-ASPNet-MVC.aspx
And working correctly.
My problem is validate these DropDownList when send the form
#Html.DropDownListFor(m => m.CountryId, Model.Countries, "[ === Select CountryId === ]", new { #Class = "textarea" })
#Html.ValidationMessageFor(m => m.CountryId, "", new { #class = "text-danger" })
#Html.DropDownListFor(m => m.StateId, Model.States, "[ === Select StateId === ]", new { #Class = "textarea" })
#Html.ValidationMessageFor(m => m.StateId, "", new { #class = "text-danger" })
In this moment if on the DropDownList no value is selected the form is validate.
How to do resolve this?
My View javascript part follow
#section Scripts {
<script src="https://code.jquery.com/jquery-1.10.2.js"
integrity="sha256-it5nQKHTz+34HijZJQkpNBIHsjpV8b6QzMJs9tmOBSo="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(function () {
$("select").each(function () {
if ($(this).find("option").length <= 1) {
$(this).attr("disabled", "disabled");
}
});
$("select").change(function () {
var value = 0;
if ($(this).val() != "") {
value = $(this).val();
}
var id = $(this).attr("id");
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: '{type: "' + id + '", value: "' + value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var dropDownId;
var list;
switch (id) {
case "CountryId":
list = response.States;
DisableDropDown("#StateId");
DisableDropDown("#CityId");
PopulateDropDown("#StateId", list);
break;
case "StateId":
dropDownId = "#CityId";
list = response.Cities;
DisableDropDown("#CityId");
PopulateDropDown("#CityId", list);
break;
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
function DisableDropDown(dropDownId) {
$(dropDownId).attr("disabled", "disabled");
$(dropDownId).empty().append('<option>[ === Select CountryId === ]</option>');
}
function PopulateDropDown(dropDownId, list) {
if (list != null && list.length > 0) {
$(dropDownId).removeAttr("disabled");
$.each(list, function () {
$(dropDownId).append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
}
</script>
}
Why not implement something like this:
if ($(this).val() == "") {
// return validation message
return;
}
else
{
value = $(this).val();
}

Get parameter into controller by using GET method in Ajax

I have this code in cshtml file
#using (Html.BeginForm("UserPermission", "UserPermision", new { area = "Admin", id = "cbbDpm", name = "cbbDpm" }, FormMethod.Post))
{
#Html.DropDownListFor(m => m.Dept, new SelectList(Model.Dept, "DepartmentName", "DepartmentName"), "-- Select Department --", new { #class = "form-control w-100", #id = "cbbDpmt", #name = "cbbDpmt" })
}
...
<div id="partialDiv">
#Html.Partial("_Table")
</div>
...
<script>
$(document).ready(function () {
$("#cbbDpmt").on("change", function () {
$.ajax(
{
url: '/Admin/UserPermision/CBBSelectedChange?dpmname' + $(this).val(),
type: 'GET',
data: "",
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#partialDiv").html(data);
},
error: function () {
alert("error");
}
});
});
});
</script>
And in controller, I have:
[HttpGet]
public PartialViewResult CBBSelectedChange(string dpmname)
{
List<AdminUserPermission> userModels = DatabaseServer.ConvertDataTable<AdminUserPermission>(DatabaseServer.Read_Table(#"SELECT *
FROM dbo.tblWFX_UserGroup AS gr
JOIN dbo.tblWFX_Department AS dpm ON gr.DepartmentName = dpm.DepartmentID
WHERE dpm.DepartmentName = " + dpmname, false));
Session["selectedDept"] = dpmname;
AdminUserPermissionParty adminUserPermissionParties = new AdminUserPermissionParty();
adminUserPermissionParties.UserPermisionModel = userModels;
return PartialView("_Table", adminUserPermissionParties);
}
I want put selected item from combobox in cshtml into function in controller. I try to research many time but I can't put selected value from cbb into string dpmname.
Please help me.
You need to use [FromUri]
[HttpGet]
public PartialViewResult CBBSelectedChange([FromUri] string dpmname)
And also change Ajax call as follows:
$.ajax(
{
url: '/Admin/UserPermision/CBBSelectedChange?dpmname=' + $(this).val(),
type: 'GET',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#partialDiv").html(data);
},
error: function () {
alert("error");
}
});
See: https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

How to return Multiple Parameters using json in mvc4?

Hi I have four fields in my view CustomerName, ContactPerson, Email, MobileNo
CustomerName , ContactPerson are Cascading Dropdown and Email and MobileNo are textboxes.
If I select the CustomerName related ContactPerson will load automatically load in ContactPerson dropdown.
If i select the Contactperson the ContactPerson related Email and PhoneNo will load automatically in Email and PhoneNo textbox. I did this all task completely and all are working fine. Now what i need is i wish to reduce the code .
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);
}
My 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)
My Json 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);
}
});
});
See my coding i wrote separate json and jquery , ajax code for Email and PhoneNo. I feel it is not good . I wish to short my code. I want to pass multiple parameter using json. I want to pass the Email and phone while selecting the ContatcPerson in ContactPerson dropdown. it also effect performance of my application. please any one give solution and suggestion for my problem.
Advance Thanks..
Why don't you return an object from your controller that contains all the information that you need?
Any object serialized to Json can be returned as a JsonResult.
You could even do anonymous types like:
var details = new { email = "test#test.com", phone = "1234567"};
return Json(details);

JQuery Autocomplete inside modal using Razor TextBoxFor

I have a partial view being display using modal. The problem that I am having is that I do understand where or when to add the jquery to the modal form that's being called. I understand that the the script is not attached to the modal. How do I do this.
My current code is not working. The autocomplete is not working.
The script is working without using the modal.
In my partial view I have a TextBoxFor with the class using "autocomplete_with_hidden".
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(model => model.Ship_To_Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(Model => Model.Ship_To_Name, new { #class = "autocomplete_with_hidden", data_url = Url.Action("AutoComplete", "Customer") })
#Html.ValidationMessageFor(model => model.Ship_To_Name, "", new { #class = "text-danger" })
</div>
</div>
</div>
The controller is using the following code.
public ActionResult Autocomplete(string term)
{
var model = db.Customers
.Where(m => term == null || m.Customer_Name.StartsWith(term))
.Take(10)
.Select(m => new
{
label = m.Customer_Name,
Id = m.Ship_To_Code
});
return Json(model, JsonRequestBehavior.AllowGet);
}
Jquery:
$(function () {
$.ajaxSetup({ cache: false, async: true });
$("a[data-modal]").on("click", function (e) {
$('#myModalContent').load(this.href, function () {
$('#myModal').modal({
//persist: true,
keyboard: true
}, 'show');
//This is a function
bindForm(this);
});
return false;
});
Jquery Create Auto Complete
var createAutoComplete = function() {
$(this).autocomplete({
minLength: 0,
source: function (request, response) {
var shipto = new Array();
//var url = $(this).attr("data_autocomplete");
var url = $(this.element).data('url');
$.ajax({
async: false,
cache: false,
type: "POST",
url: url,
data: { "term": request.term },
success: function (data) {
for (var i = 0; i < data.length ; i++) {
shipto[i] = { label: data[i].Value, Id: data[i].Key };
}
}
});
response(shipto);
},
select: function (event, ui) {
// fill selected shipto details on form
var url = "/GetShipTo/Customer"
$.ajax({
cache: false,
async: false,
type: "POST",
url: url,
data: { "id": ui.item.id },
success: function (data) {
$('.modal-body').show();
$("#Ship_To_Address_1").html(data.Ship_To_Address_1)
$("#Ship_To_Address_2").html(data.Ship_To_Address_2)
$("#Ship_To_City_Name").html(data.Ship_To_City_Name)
$("#Ship_To_State_Code").html(data.Ship_To_State_Code)
$("#Ship_To_Zip_Code").html(data.Ship_To_Zip_Code)
action = data.Action;
},
});
}
});
};
$('#myModalContent').find('.autocomplete_with_hidden').each(createAutoComplete);
});
Jquery Bind Form:
function bindForm(dialog) {
$('form', dialog).submit(function () {
$.ajaxSetup({
cache: false
})
$('#progress').show();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$('#myModal').modal('hide');
$('#myModal').removeData("modal");
$('#progress').hide();
location.reload();
} else {
$('#progress').hide();
$('#myModalContent').html(result);
bindForm();
}
}
});
return false;
});
}

MVC:Textbox autopopulate not working

I am trying to implement auto-populate on a particular textbox but it is not working so far. Here's my code. What am I missing?
VIEW:
<script type="text/javascript">
$(document).ready(function () {
$("#lead-organisation").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Project/AutoCompleteOrganisation",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Organisation, value: item.Organisation };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
</script>
<div class="form-group">
<label for="#Html.IdFor(x => x.Organisation)">
#Html.DisplayNameFor(x => x.Organisation)
</label>
#Html.TextBoxFor(x => x.Organisation, new { #class = "form-control", data_project = "organisation", editorId="lead-organisation" })
#Html.ValidationMessageFor(x => x.Organisation)
</div>
My CONTROLLER:
[AjaxOnly]
public ActionResult AutoCompleteOrganisation(string term)
{
var taxonomy = DependencyResolver.Current.GetService<TaxonomyHelper>();
var organisationList = new ProjectOrganisationModel();
organisationList.Organisation = taxonomy.GetOrganisations();
var result = from org in organisationList.Organisation
where org.Name.ToLower().Contains(term.ToLower())
select org.Name;
return Json(result, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
}
I have also downloaded this:jquery.autocomplete.js and added it on my BundleConfig.cs
.Include("~/Scripts/jquery.autocomplete.js")
I was able to finally make it work.
Used this instead:
<script type="text/javascript">
$(document).ready(function () {
$("#lead-organisation").autocomplete({
source: '#Url.Action("AutoCompleteOrganisation", "Project")'
});
})
</script>
For controller:
public JsonResult AutoCompleteOrganisation(string term)
{
var taxonomy = DependencyResolver.Current.GetService<TaxonomyHelper>();
var organisationList = new ProjectOrganisationModel();
organisationList.Organisation = taxonomy.GetOrganisations();
var match = organisationList.Organisation.Where(x => x.Name.ToLower().Contains(term.ToLower())).
Select(e => e.Name).Distinct().ToList();
return Json(match, JsonRequestBehavior.AllowGet);
}
Then I did not download any autocomplete plugin, instead just use:
jquery-ui-1.10.4.custom.css
jquery-ui-1.10.4.custom.js
jquery-2.1.1.js
Thank you for answering my queries.

Categories

Resources