Auto populate Textbox based on Dropdown selection - c#

I want to auto-populate a textbox based on dropdown selection in MVC, using jquery, razor view and controller, from a model called Supplier, that has SupplierID, and Company_Registration_Number as variables. I have managed to do it as cascade dropdown, but i'm failingto populate #Html.EditorFor.
My controller :
public JsonResult GetCompanyRegistrationNumberId(int id)
{
var suppliers = db.Suppliers.Where(p => p.SupplierID == id).ToList();
var result = (from r in suppliers
select new
{
id = r.SupplierID,
name = r.Company_Registration_Number
}).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
My JQuery:
$(function () {
if ($("#SupplierID").val() == '0') {
var productDefaultValue = "<option value='0'>--Select a category first--</option>";
$("#Company_Registration_Number").html(productDefaultValue).show();
}
$("#SupplierID").change(function () {
var selectedItemValue = $(this).val();
alert("cert");
var ddlProducts = $("#Company_Registration_Number");
$.ajax({
cache: false,
type: "GET",
url: '#Url.Action("GetCompanyRegistrationNumberId", "Order")',
data: { "id": selectedItemValue },
success: function (data) {
ddlProducts.html('');
$.each(data, function (id, option) {
ddlProducts.append($('<option></option>').val(option.id).html(option.name));
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Found error to load product!!.');
}
});
});
});
My Razor view:
<div class="form-group">
#Html.LabelFor(model => model.Company_Registration_Number, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Company_Registration_Number, new { #id = "Company_Registration_Number" })
#Html.ValidationMessageFor(model => model.Company_Registration_Number, "", new { #class = "text-danger" })
</div>
</div>
Thanks in advance.

Related

Dependent dropdownlist in ASP.NET MVC

At present I have two tables (Teams and Employees)
I am populating the dropdownList for Teams perfectly, next I am trying to populate the second dropdownlist depending on the selectedId of Teams for Employees.
Controller:
// GET: CalView
public ActionResult Index(string ses, string DH)
{ //Team Lead Members
var eID = Convert.ToInt32(Session["currentEmployeeID"]);
var EmpID = Session["currentEmpID"];
Employee obj = (from o in db.Employees
where o.EnrollNumber == EmpID
select o).FirstOrDefault();
Department dept = (from dep in db.Departments
where dep.LeadBy == obj.EmployeeId
select dep).FirstOrDefault();
//this works fine
ViewBag.showTeams = new SelectList(db.Teams.Where(tm => (tm.DeptID == dept.DepartmentId) && (dept.LeadBy == eID)), "TeamID","Name");
//this obviously does not
ViewBag.showMembers = new SelectList(db.Employees.Where(empt => (empT.TeamID == selectedIdFromPreviousDropDownList), "EmployeeID", "Employee"));
return View();
}
View:
if ((Session["UT"] == "DD") && (#ViewBag.DeptLead != null))
{
//this works
#Html.DropDownList("showTeams", null, "-Select Team-", htmlAttributes: new { #class = "form-control" })
//this does not work
#Html.DropDownList("showMembers", null, "-Select Team-", htmlAttributes: new { #class = "form-control" })
}
Do I need some AJAX call? or perhaps a POST method? Totally new to MVC.
Do I need some AJAX call? or perhaps a POST method? Okay then, lets do it this way:
Give your DropdownLists some id's probably:
#Html.DropDownList("showTeams", null, "-Select Team-", htmlAttributes: new { id = "ddshowTeams", #class = "form-control" })
#Html.DropDownList("showMembers", null, "-Select Team-", htmlAttributes: new {id = "ddshowMembers", #class = "form-control" })
Create a jsonResult function, GetMembers and some Magic right there:
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#ddshowTeams").change(function () {
console.log("pehla andar");
$("#ddshowMembers").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetMembers")',
dataType: 'json',
data: { id: $("#ddshowTeams").val() },
success: function (mems) {
console.log("wich ayaeee");
// states contains the JSON formatted list
// of states passed from the controller
$.each(mems, function (i, member) {
$("#ddshowMembers").append('<option value="'
+ member.Value + '">'
+ member.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
and in your controller:
public JsonResult GetMembers(int id)
{
return Json(new SelectList(db.Employees.Where(empt => (empt.TeamId == id)), "EmployeeID", "FirstName"));
}

Refreshing #Html.ListBox content with results from ajax call in MVC

I have two #Html.ListBox in my view:
IEnumerable<Models.CategoryModel> categories = ViewBag.AllCategories;
IEnumerable<Models.TypeModel> types = ViewBag.AllTypes;
#Html.Label("Category", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.ListBox("CategoriesFilter", new MultiSelectList(categories, "CatID", "Category"), new { #class = "chosen-select" })
</div>
#Html.Label("Type", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.ListBox("TypesFilter", new MultiSelectList(types, "TID", "Description"), new { #class = "chosen-select" })
</div>
When the user selects/deselects a category, I need to refresh the types in #Html.ListBox("TypesFilter"). I am doing an ajax call as follows:
$("#CategoriesFilter").change(function () {
setTypesByCategory();
});
function setTypesByCategory() {
var categoryIDs = ($('#CategoriesFilter').val());
$.ajax({
url: "#(Url.Action("SetTypesByCategory", "Issues"))",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: '{ "categoryIDs" : "' + categoryIDs + '" }',
success: function (data) {
$.each(data, function () {
$.each(this, function (k, v) {
window.alert("success !!!" + k + " test " + this.STID);
});
});
$("#TypesFilter").empty();
$("#TypesFilter").val(data.TypesData);
}
});
}
And in my controller:
[System.Web.Mvc.HttpPost]
public JsonResult SetTypesByCategory(string categoryIDs)
{
string[] categories = categoryIDs.Split(',');
List<TypeModel> filterdTypesList = new List<TypeModel>();
foreach (var catID in categories)
{
foreach (var type in types.Where(m => m.CatID == Int32.Parse(catID)))
{
filterdTypesList.Add(type);
}
}
int modelCount = filterdTypesList.Count();
IEnumerable<TypeModel> filterdTypes = filterdTypesList;
return Json(new { TypesData = filterdTypes, ModelCount = modelCount });
}
First, the types list box is not being empty when using $("#TypesFilter").empty();. And how can i populate this listbox with the obtained results?

Autocomplete dropdown in MVC5?

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

How to pass multiple parameter to ajax and from ajax to controller in mvc4?

My First Question
Hi i have 4 fields in my view FromDate,ToDate,CustomerName, Count.
I want to pass the value of FromDate,ToDate,CustomerName to single Action and have to get the value in Count Textbox. Help me to solve this problem.
My second question
public JsonResult GetSalesOrderCountByCustomer(Guid customerID, DateTime fromdate,DateTime Todate)
{
var salescount = (from sc in db.SalesOrders where sc.CustomerID == customerID select sc.SalesOrderID).Count();
return Json(salescount, JsonRequestBehavior.AllowGet);
}
The above code get the total SalesOrder count of customer now what i need is i want to get the sales order count of customer(which i select in Dropdown) between FromDate(Which i select in view) and ToDate(which i select in view). how i alter this query for my requirement.
My View
<div class="col-sm-4">
<div class="form-group">
#Html.Label("FromDate", new { #class = "control-label" })
#Html.TextBoxFor(model => model.FromDate, new { #class = "form-control", type = "text"})
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
#Html.LabelFor(model => model.ToDate)
#Html.TextBoxFor(model => model.ToDate, new { #class = "form-control", type = "text" })
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
#Html.LabelFor(model => model.CustomerName)
#Html.DropDownList("CustomerID","Select")
#Html.ValidationMessageFor(model => model.CustomerName)
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
#Html.LabelFor(model => model.count)
#Html.TextBoxFor(model => model.count, new { #class = "form-control", type = "text"})
#Html.ValidationMessageFor(model => model.count)
</div>
</div>
My jquery
<script src="~/Scripts/jquery-ui-1.8.24.js"></script>
<script src="~/Scripts/jquery-ui-1.8.24.min.js"></script>
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>
<script src="~/Scripts/jquery-ui-1.11.0.js"></script>
<script type ="text/javascript">
$(function () {
$.ajax(
//url: "/VisitorsForm/GetCustomers",
'#Url.Action("GetCustomers","Report")', {
type: "GET",
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#CustomerID').append('<option value="' + value.CustomerID + '">' + value.DisplayName + '</option>');
});
}
});
});
$("#CustomerID").change(function () {
//$('#ContactID').empty();
alert("hhh");
var req = {
CustomerID: $("#CustomerID").val(),
FromDate: $("#FromDate").val(),
ToDate: $("ToDate").val()
}
$.ajax(
'#Url.Action("GetSalesOrderCountByCustomer", "Report")', {
type: "GET",
dataType: "json",
async: false,
data: JSON.stringify(req),
error: function (ex) {
alert('Failed to retrieve Email.' + ex);
},
beforeSend: function () {
},
success: function (data) {
$("#count").val(data);
}
});
});
</script>
My Controller
[HttpGet]
public ActionResult NewExistingCustomer( CustomerViewModel cvm)
{
ViewBag.CustomerID = new SelectList(db.Customers, "CustomerID", "DisplayName");
return View();
}
public JsonResult GetCustomers()
{
return Json(db.Customers.ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult GetSalesOrderCountByCustomer(Guid customerID, DateTime fromdate,DateTime Todate)
{
var salescount = (from sc in db.SalesOrders where sc.CustomerID == customerID select sc.SalesOrderID).Count();
return Json(salescount, JsonRequestBehavior.AllowGet);
}
}}

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);

Categories

Resources