I have a dropdownlist contains a list of products which binds from database. I want to load selected product Data.
here is my code in view
#Html.DropDownListFor(model => model.ProductName, new SelectList(Model.ProductsList, "ProductID", "ProductName"), new
{
id = "Productslist",
#class = "GreenDropDownListStyle",
#datastyle = "dropdown",
#onchange = "FillProduct()"
})
I had use java Script code to send select Product Id then get it's data
<script type="text/javascript">
$(document).ready(function () {
$("#Productslist").change(function () {
debugger;
var selectedIndex = $(this).val();
var divH = document.getElementById(selectedIndex);
if (selectedIndex > 0) {
$.ajax(
{
url: '/Inventory/ViewProduct',
type: 'GET',
data: { ProductID: selectedIndex },
contentType: 'application/json; charset=utf-8',
success: function (data) {
///
},
error: function () {
alert("error");
}
});
}
else {
divH.style.visibility = 'hidden'; // Hide
}
});
});
</script>
the issue that this code send the selected index not the is for the selected product also its send the id as a string so it never go to my condition
last thing in case of succeed what i should write
it solved by
var ProductID = this.value;
Related
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();
}
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
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
i have a View, and on a button click i need that open me a JQueryDialog loaded from PartialView that have inside a list of items... on click of one of these items, i need that in the same JQueryDialog open another PartialView, for editing this item, so a simple List/Detail nested in a JQueryDialog..
i post a sample..
http://sdrv.ms/15hG92K
VIEW
$('#dialogReferences').dialog({
autoOpen: false,
width: dWidth,
resizable: false,
title: 'TEST',
modal: true,
draggable: false,
position: ['top', 100],
open: function (event, ui)
{
var id = $(this).data('id');
var url = '#Url.Action("ListItem", "Home")';
$(this).dialog().load(url, function ()
{
$(document).unbind("click", ".k-grid-Edit").on("click", ".k-grid-Edit", function (evt)
{
evt.preventDefault();
var grid = $("#contactsGrid").data("kendoGrid");
var selectedData = grid.dataItem(grid.select());
if (selectedData)
{
var urlEdit = '#(Html.Raw(#Url.Action("ItemEdit", "Home", new { selectedId = "_selectedId_" })))';
urlEdit = urlEdit.replace("_selectedId_", selectedData.Id);
$('#dialogReferences').dialog().load(urlEdit);
}
});
$(document).unbind("click", ".k-grid-Delete").on("click", ".k-grid-Delete", function (evt)
{
evt.preventDefault();
var grid = $("#contactsGrid").data("kendoGrid");
var selectedData = grid.dataItem(grid.select());
if (selectedData)
{
var urlDelete = '#(Html.Raw(#Url.Action("ItemDelete", "Home", new { selectedId = "_selectedId_" })))';
urlDelete = urlDelete.replace("_selectedId_", selectedData.Id);
$.ajax({
url: urlDelete,
type: 'POST',
cache: false,
dataType: 'json',
success: function (result)
{
if (result.success)
{
alert('DELETE');
grid.dataSource.read();
}
}
});
}
});
});
}
});
EDIT
$(document).ready(function ()
{
$.ajaxSetup({ cache: false });
$(document).unbind("click","#btnCancel").one("click", "#btnCancel", function (evt)
{
evt.preventDefault();
var model = #Html.Raw(Json.Encode(Model));
var urlList = '#Url.Action("ListItem", "Home")';
$('#dialogReferences').dialog().load(urlList, function ()
{
$(document).unbind("click", ".k-grid-Edit").one("click", ".k-grid-Edit", function (evt)
{
evt.preventDefault();
var grid = $("#contactsGrid").data("kendoGrid");
var selectedData = grid.dataItem(grid.select());
if (selectedData)
{
var urlEdit = '#(Html.Raw(#Url.Action("ItemEdit", "Home", new { selectedId = "_selectedId_" })))';
urlEdit = urlEdit.replace("_selectedId_", selectedData.Id);
$('#dialogReferences').dialog().load(urlEdit);
}
});
$(document).unbind("click", ".k-grid-Delete").on("click", ".k-grid-Delete", function (evt)
{
evt.preventDefault();
var grid = $("#contactsGrid").data("kendoGrid");
var selectedData = grid.dataItem(grid.select());
if (selectedData)
{
var urlDelete = '#(Html.Raw(#Url.Action("ItemDelete", "Home", new { selectedId = "_selectedId_" })))';
urlDelete = urlDelete.replace("_selectedId_", selectedData.Id);
$.ajax({
url: urlDelete,
type: 'POST',
cache: false,
dataType: 'json',
success: function (result)
{
if (result.success)
{
alert('DELETE');
grid.dataSource.read();
}
}
});
}
});
});
})
});
if i try to 'open file dialog' and delete without edit, it call delete action one time, and it's ok.
but if you try to enter in edit and than come back with cancel to the list, and delete, it call twice.
Someone can give me and advice?
I have two dropdownlist. The selected value from the first one loads the other. How do I do that when I have the helper methods in a controller?
#using (Html.BeginForm())
{
<div>
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td><b>Select a District:</b></td>
<td>#Html.DropDownListFor(m => m.DistrictId, ViewData["DMManagers"] as IEnumerable<SelectListItem>, "Select One")</td>
</tr>
<tr>
<td><b>Select a TM:</b></td>
<td>#Html.DropDownListFor(m => m.TMId, ViewData["TMManagers"] as IEnumerable<SelectListItem>, "Select One")</td>
</tr>
</table>
</div>
}
private void LoadDistrictManagers()
{
var _DMS = (from c in SessionHandler.CurrentContext.ChannelGroups
join cgt in SessionHandler.CurrentContext.ChannelGroupTypes on c.ChannelGroupTypeId equals cgt.ChannelGroupTypeId
where cgt.Name == "District Manager"
select new { c.ChannelGroupId, c.Name }).OrderBy(m => m.Name);
ViewData["DMManagers"] = new SelectList(_DMS, "ChannelGroupId", "Name");
}
private void LoadTerritoryManagers(int districtId)
{
var _TMS = (from c in SessionHandler.CurrentContext.ChannelGroups
join cgt in SessionHandler.CurrentContext.ChannelGroupTypes on c.ChannelGroupTypeId equals cgt.ChannelGroupTypeId
where cgt.Name == "Territory" && c.ParentChannelGroupId == districtId
select new { c.ChannelGroupId, c.Name }).OrderBy(m => m.Name);
ViewData["TMManagers"] = new SelectList(_TMS, "ChannelGroupId", "Name");
}
public ActionResult SummaryReport()
{
DistrictManagerModel model = new DistrictManagerModel();
LoadDistrictManagers();
return View("AreaManager", model);
}
Give both dropdowns unique IDs using the HTTPAttributes field:
#Html.DropDownListFor(m => m.DistrictId, ViewData["DMManagers"] as IEnumerable<SelectListItem>, "Select One", new {#id="ddlDMManagers"})
2nd dropdown should be initialized as an empty list:
#Html.DropDownListFor(m => m.TMId, Enumerable.Empty<SelectListItem>(), new {#id="ddlTMManagers"})
If you don't mind using jQuery ajax to update the 2nd dropdown when a 'change' event is triggered on the 1st dropdown:
$(function() {
$('select#ddlDMManagers').change(function() {
var districtId = $(this).val();
$.ajax({
url: 'LoadTerritoryManagers',
type: 'POST',
data: JSON.stringify({ districtId: districtId }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$.each(data, function (key, TMManagers) {
$('select#ddlTMManagers').append('<option value="0">Select One</option>');
// loop through the TM Managers and fill the dropdown
$.each(TMManagers, function(index, manager) {
$('select#ddlTMManagers').append(
'<option value="' + manager.Id + '">'
+ manager.Name +
'</option>');
});
});
}
});
});
});
Add this class to your controller namespace:
public class TMManager
{
public int Id {get; set;}
public string Name {get; set;}
}
You will need to update your controller action, LoadTerritoryManagers(), to respond to the ajax request and return a JSON array of {Id,Name} objects.
[HttpPost]
public ActionResult LoadTerritoryManagers(int districtId)
{
var _TMS = (from c in SessionHandler.CurrentContext.ChannelGroups
join cgt in SessionHandler.CurrentContext.ChannelGroupTypes on c.ChannelGroupTypeId equals cgt.ChannelGroupTypeId
where cgt.Name == "Territory" && c.ParentChannelGroupId == districtId
select new TMManager(){ Id = c.ChannelGroupId, Name = c.Name }).OrderBy(m => m.Name);
if (_TMS == null)
return Json(null);
List<TMManager> managers = (List<TMManager>)_TMS.ToList();
return Json(managers);
}
Use the following code. It is used in my project. For Zone and Region I used two drop-down list. On change Zone data I loaded the Region drop-down.
In View page
#Html.DropDownList("ddlZone", new SelectList(#ViewBag.Zone, "Zone_Code", "Zone_Name"), "--Select--", new { #class = "LoginDropDown" })
#Html.DropDownList("ddlRegion", Enumerable.Empty<SelectListItem>(), new { #class = "LoginDropDown" })
The Zone need to load when the view page is load.
In the controller write this method for Region Load
[WebMethod]
public JsonResult LoadRegion(string zoneCode)
{
ArrayList arl = new ArrayList();
RASolarERPData objDal = new RASolarERPData();
List<tbl_Region> region = new List<tbl_Region>();
region = erpDal.RegionByZoneCode(zoneCode);
foreach (tbl_Region rg in region)
{
arl.Add(new { Value = rg.Reg_Code.ToString(), Display = rg.Reg_Name });
}
return new JsonResult { Data = arl };
}
Then use the following JavaScript
<script type="text/javascript">
$(document).ready(function () {
$('#ddlZone').change(function () {
LoadRegion(this.value);
});
function LoadRegion(zoneCode) {
$.ajax({
type: "POST",
url: '#Url.Action("LoadRegion", "RSFSecurity")',
data: "{'zoneCode':'" + zoneCode + "'}",
contentType: "application/json; charset=utf-8",
dataType: 'json',
cache: false,
success: function (data) {
$('#ddlRegion').get(0).options.length = 0;
$('#ddlRegion').get(0).options[0] = new Option("--Select--", "0");
$.map(data, function (item) {
$('#ddlRegion').get(0).options[$('#ddlRegion').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Failed to load Item");
}
});
}
});
</script>
We can use the jquery to get and fill the dropdown like this:
<script>
function FillCity() {
var stateId = $('#State').val();
$.ajax({
url: '/Employees/FillCity',
type: "GET",
dataType: "JSON",
data: { State: stateId},
success: function (cities) {
$("#City").html(""); // clear before appending new list
$.each(cities, function (i, city) {
$("#City").append(
$('<option></option>').val(city.CityId).html(city.CityName));
});
}
});
}
</script>
For more detail see
MVC DropDownListFor fill on selection change of another dropdown