MVC dropdown list with json data and chosen - javascript

I'm trying to populate dropdown list with jsonResult data on a second list
on change event. That works just fine. But I also want to use chosen on that list, and with that list is empty. It looks like chosen is not picking up list update. I'm pretty new in this so please help
First list:
<div class="col-md-10">
#Html.DropDownList("tipopreme_TipOpremeID", null, htmlAttributes: new { #class = "form-control", #onchange = "PopuniDropOpreme()" })
</div>
Second List:
#Html.DropDownListFor(x => x.ModelOpreme_ModelOpremeID, new SelectList(Enumerable.Empty<SelectListItem>()))
Controller:
public JsonResult getOpremaPoTipu(int? tipid)
{
List<SelectListItem> lista = new List<SelectListItem>();
if (tipid != null)
{
foreach (var item in db.ModelOpremes.Where(x=>x.TipOpreme_TipOpremeID==tipid))
{
lista.Add(new SelectListItem { Text = item.PunNaziv, Value = item.ModelOpremeID.ToString()});
}
}
else
{
foreach (var item in db.ModelOpremes)
{
lista.Add(new SelectListItem { Text = item.PunNaziv, Value = item.ModelOpremeID.ToString() });
}
}
return Json(lista, JsonRequestBehavior.AllowGet);
}
Script:
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/chosen.jquery.min.js"></script>
<link href="~/Content/chosen.min.css" rel="stylesheet" />
<script type="text/javascript">
$(".chzn-select").chosen();
$("#ModelOpreme_ModelOpremeID").chosen();
function PopuniDropOpreme() {
var tip = $("#tipopreme_TipOpremeID").val();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/Opremas/getopremapoTipu?selectedValue=" + tip,
data: "{}",
dataType: "Json",
success: function (data) {
$('.ddlProjectvalue').find('option').remove();
$(data).each(function (index, item) {
$("#ModelOpreme_ModelOpremeID").append($('<option></option>').val(item.Value).html(item.Text));
});
$("ModelOpreme_ModelOpremeID").chosen("destroy").chosen();
},
error: function ajaxError(response) {
alert(response.status + ' ' + response.statusText);
}
});
}
</script>

You got some errors in your code:
- url: "/Opremas/getopremapoTipu?selectedValue=" + tip, //wrong param name
- $('.ddlProjectvalue').find('option').remove(); //wrong id
They should be:
- url: "/Opremas/getopremapoTipu?tipid=" + tip
- $('#ModelOpreme_ModelOpremeID').find('option').remove();
You can follow my sample. Hope to help, my friend!
public class Test
{
public int Id { get; set; }
public string Value { get; set; }
}
public JsonResult GetData(int? selectedValue)
{
List<SelectListItem> lista = new List<SelectListItem>();
if (selectedValue != null)
{
foreach (var item in Data().Where(t=>t.Id == selectedValue))
{
lista.Add(new SelectListItem
{
Text = item.Id.ToString(),
Value = item.Value
});
}
}
else
{
foreach (var item in Data())
{
lista.Add(new SelectListItem { Text = item.Id.ToString(), Value = item.Value.ToString() });
}
}
return Json(lista, JsonRequestBehavior.AllowGet);
}
private List<Test> Data()
{
var data = new List<Test>
{
new Test{Id = 1, Value = "A1"},
new Test{Id = 1, Value = "A2"},
new Test{Id = 1, Value = "A3"},
new Test{Id = 1, Value = "A4"},
new Test{Id = 2, Value = "B1"},
new Test{Id = 3, Value = "C1"},
new Test{Id = 4, Value = "D1"},
};
return data;
}
And code in View:
#{
ViewBag.Title = "About";
}
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.css">
</head>
<body style="margin-top:50px;">
<script type="text/javascript">
$(function () {
$(".chzn-select").chosen();
$("#ModelOpreme_ModelOpremeID").chosen();
$(".chzn-select").chosen().change(function () {
var id = $(this).val();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/Home/GetData?selectedValue=" + id,
data: "{}",
dataType: "Json",
success: function (data) {
$('#ModelOpreme_ModelOpremeID').find('option').remove();
$(data).each(function (index, item) {
$("#ModelOpreme_ModelOpremeID").append($('<option></option>').val(item.Text).html(item.Value));
});
$("#ModelOpreme_ModelOpremeID").chosen("destroy").chosen();
},
error: function ajaxError(response) {
alert(response.status + ' ' + response.statusText);
}
});
});
});
</script>
<select class="chzn-select" name="faculty" style="width:200px; margin:10%;">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<br />
<select id="ModelOpreme_ModelOpremeID" style="width:200px; ">
</select>
</body>
</html>

Related

Sending data from View to Action

How do I send some data from the view back to the controller?
This is the select from where I get the data (sel1):
<div class="form-group" style="margin: 0 auto;">
<label for="sel1">Select a cat breed:</label>
<select class="form-control" id="sel1">
#foreach (var item in Model)
{
<option>
#Html.DisplayFor(modelItem => item.BreedName)
</option>
}
</select>
</div>
This is the script I tried to use to send data back:
<script>
$(document).ready(function () {
loadJasonData();
$("#sel1").change(function () {
loadJasonData();
});
});
function loadJasonData() {
$.ajax({
type: "POST",
url: "CatDetails",
//url: "/CatCompare/CatDetails", i also tried this of url
cache: false,
dataType: "json",
data: { name: $("#sel1").val() }
})
}
And finally the controller:
[HttpPost]
[HttpGet]
public ActionResult CatDetails(string name)
{
var breedName = db.Breeds.FirstOrDefault(b => b.BreedName == name);
ViewBag.name = breedName.BreedName;
ViewBag.lifeSpan = breedName.Lifespan;
ViewBag.height = breedName.Height;
ViewBag.weight = breedName.Weight;
ViewBag.shortDescription = breedName.ShortDescription;
return View();
}
First of all you have to add option value to your select:
<div class="form-group" style="margin: 0 auto;">
<label for="sel1">Select a cat breed:</label>
<select class="form-control" id="sel1">
#foreach (var item in Model)
{
<option value='#item.BreedName'>
#Html.DisplayFor(modelItem => item.BreedName)
</option>
}
</select>
</div>
Then change your loadJasonData() method to this
function loadJasonData() {
$.ajax({
type: "POST",
url: "/CatCompare/CatDetails",
cache: false,
dataType: "json",
data: { name: $("#sel1 option:selected").val() }
})
}
at the last remove [HttpGet] in your action
[HttpPost]
public ActionResult CatDetails(string name)
{
var breedName = db.Breeds.FirstOrDefault(b => b.BreedName == name);
ViewBag.name = breedName.BreedName;
ViewBag.lifeSpan = breedName.Lifespan;
ViewBag.height = breedName.Height;
ViewBag.weight = breedName.Weight;
ViewBag.shortDescription = breedName.ShortDescription;
return View();
}
Note: Your action returns a view. If you want to return json result you have to use return Json(yourData);

Loading the aspx combobox at client side

I have used aspx combobox and bind the values at the client side through ajax call, the values are loaded but was not displayed in the combobox, i want to know where i did the mistake
please find the code below:
public static List<string> GetDepartments()
{
ABTestNewEntities obj = new ABTestNewEntities();
List<string> lst = new List<string>();
lst.Add(string.Format("{0}-|-{1}", 0, "Please Select"));
lst.Add(string.Format("{0}-|-{1}", 1, "Develop"));
lst.Add(string.Format("{0}-|-{1}", 2, "Test"));
lst.Add(string.Format("{0}-|-{1}", 3, "HR"));
return lst;
}
$(document).ready(function () {
alert("inside function");
$("#btn").click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "NewOrder.aspx/GetDepartments",
data: "",
datetype: "json",
async: false,
success: function (data) {
var response = data.d;
$("#ddldepartment").empty();
for (var i = 0; i < response.length; i++) {
var item = response[i].split("-|-");
var Option = "<option value='" + item[0] + "'>" + item[1] + "</option>";
Option.text = item[1];
Option.value = item[0];
$("#ddldepartment").append(Option);
}
return false;
//});
},
error: function (data) {
alert("Error");
alert(data.error);
return false;
}
});
return false;
});
return false;
});
use [WebMethod]
[WebMethod]
public static List<string> GetDepartments()
{
List<string> lst = new List<string>();
lst.Add(string.Format("{0}-|-{1}", 0, "Please Select"));
lst.Add(string.Format("{0}-|-{1}", 1, "Develop"));
lst.Add(string.Format("{0}-|-{1}", 2, "Test"));
lst.Add(string.Format("{0}-|-{1}", 3, "HR"));
return lst;
}
You can use AddItem() Method
here are the References about dynamic load item in the Combobox at clientside(js)
https://docs.devexpress.com/AspNet/js-ASPxClientComboBox.AddItem(text)
and this is the example or demo
https://codecentral.devexpress.com/e1332/

Jquery Ajax call does not call Asp.net mvc controller action method

I have two drop-downs State and City.According to State selected city should be loaded.So I use State drop-down change event to call ajax method to populate City drop-down.
HTML
<div class="row">
<div class="col-sm-6 ">
<div class="form-group">
<label>State</label>
#Html.DropDownListFor(m => m.State, Model.States, "Please select a State", new { #class = "form-control" })
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6 ">
<div class="form-group">
<label>Cities</label>
#Html.DropDownListFor(m => m.CityRegisterScreen, new SelectList(string.Empty, "Id", "Name"), "Please select a city", new { #class = "form-control" })
</div>
</div>
</div>
JavaScript
This Contains Jquery and Javascript Code.
$(document).ready(function () {
$("#State").on("change", function () { // whenever a selection is made
$("#CityRegisterScreen").empty();
var id = $("#State").val();
$.ajax({
type: 'GET', // we are calling json method
url: '#Url.Action("GetCitiesByDistrict", "Account")',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: { id: id },
success: function (cities) {
$.each(cities, function (i, city) {
$("#CityRegisterScreen").append('<option value="' + city.value + '">' +
city.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve cities.' + ex);
}
});
return false;
});
});
Controller
This is the controller action method which returns Json
public JsonResult GetCitiesByDistrict(int id)
{
List<SelectListItem> cities = new List<SelectListItem>();
var city = new List<City>();
using (ApplicationDbContext context = new ApplicationDbContext())
{
city = context.Cities.Where(e => e.DistrictId == id).ToList();
}
return Json(new SelectList(city, "Id", "Name"), JsonRequestBehavior.AllowGet);
}
Issue is when ajax method is called it doesn't call the Action method in controller.I double checked the URL and DataType it's all perfect.But Action method didn't get called.
It is silly!!! How did i miss this. Thank You #Rajshekar Reddy for your comment it guided me. I am missing [AllowAnonymous] attribute.
[AllowAnonymous]
public JsonResult GetCitiesByDistrict(int id)
{
List<SelectListItem> cities = new List<SelectListItem>();
var city = new List<City>();
using (ApplicationDbContext context = new ApplicationDbContext())
{
city = context.Cities.Where(e => e.DistrictId == id).ToList();
}
return Json(new SelectList(city, "Id", "Name"), JsonRequestBehavior.AllowGet);
}
This is a code for loading States according to selected country. Try this solution.
HTML
#Html.DropDownListFor(model => model.CustAddr_Country_ID, Model.Countries, "Select Country", htmlAttributes: new { #class = "disableInput", #id = "ddlstate", #onchange = "javascript:GetCity(this.value);" })
#Html.DropDownListFor(model => model.CustAddr_State_ID, ViewBag.CustAddr_State_ID as SelectList, "Select State", htmlAttributes: new { #class = "disableInput"})
Script
function GetCity(_stateId) {
$("#CustAddr_State_ID").empty().trigger('change');
var newOption = new Option("Select State", 0, true, true);
$("#CustAddr_State_ID").append(newOption).trigger('change');
if (_stateId != null && _stateId != "") {
var url = "/Ajax/GetCityByStaeId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
for (var x = 0; x < data.length; x++) {
var newOption = new Option(data[x].Text, data[x].Value, true, true);
$("#CustAddr_State_ID").append(newOption).trigger('change');
}
$('#CustAddr_State_ID').val('0').trigger('change');
},
error: function (reponse) {
//alert("error : " + reponse);
}
});
}
}
Controller
[HttpPost]
public ActionResult GetCityByStaeId(int stateid)
{
List<State> objcity = new List<State>();
objcity = _state.GetState().Where(m => m.State_Country_ID == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "State_ID", "State_Name", 0);
return Json(obgcity);
}

Autocomplete dropdownlist not working

I went through a lot of guides and stacloverflow posts, but i still don't manage to make it work. I'm still new in javascript, and it's hard for me to figure if it's the script or not.
The main issue i got is the fact I'm not able to debbug it properly, i mean, i can't find where and why it's not working, i just know it doesn't.
Here is my Controller :
Entities db = new Entities();
// GET: DynamicListe
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Index(string Prefix)
{
//Searching records from list using LINQ query
var client = (from c in db.Clients
where c.Nom.Contains(Prefix)
select new { c.Nom });
return Json(client, JsonRequestBehavior.AllowGet);
}
Here is my View :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#client").autocomplete({
source: function (request, response) {
var customer = new Array();
$.ajax({
url: "/DynamicListe/Index",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
for (var i = 0; i < data.length ; i++) {
customer[i] = { label: data[i].Value, Id: data[i].Key }
}
}
});
response(customer);
},
messages: {
noResults: "", results: ""
}
});
})
</script>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="client">
<div class="col-md-12">
#Html.TextBox("client")
</div>
</div>
</div>
}
I got the right amount of answers (when i press "w" i got 13 results which is correct according to my db), but it's all empty. I've tried severals ways to display the json datas, but i don't know how to make it work..
Edit : correct controller and view :
view :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#client").autocomplete({
source: function (request, response) {
var customer = new Array();
$.ajax({
url: "/DynamicListe/Index",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Text, value: item.Value};
}))
}
});
},
messages: {
noResults: "", results: ""
}
});
})
</script>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="client">
<div class="col-md-12">
#Html.TextBox("client")
</div>
</div>
</div>
}
controller :
[HttpPost]
public JsonResult Index(string Prefix)
{
List<SelectListItem> list = new List<SelectListItem>();
var client = (from c in db.Clients
where c.Nom.Contains(Prefix)
select c).ToArray();
for (int i = 0; i < client.Length; i++)
{
list.Add(new SelectListItem
{
Text = client[i].Nom,
Value = client[i].ClientID.ToString()
});
}
return Json(list, JsonRequestBehavior.AllowGet);
}
You're returning your response before it has been received.
In here
source: function (request, response) {
var customer = new Array();
$.ajax({
url: "/DynamicListe/Index",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
for (var i = 0; i < data.length ; i++) {
customer[i] = { label: data[i].Value, Id: data[i].Key }
}
}
});
response(customer);
},
Move the line response(customer) inside the ajac success callback.
You textbox does not have an ID. you have to add for yout textbox : #Id="client"

Ajax call to Controller arrives empty in MVC 4

I'm trying to populate one select when the onchange of another select is called. Below is what I have built. My GetLine ActionResult breakpoint is being hit, but the parameter breweryCode is null. The method errors at that point. What am I missing?
Controller:
public ActionResult Index()
{
List<Brewery> breweries = BuildMockBrewery();
ViewBag.Breweries = new SelectList(breweries.AsEnumerable(), "BreweryCode", "BreweryDescription");
return View();
}
public ActionResult GetLine(string breweryCode)
{
List<PackagingLine> packagingLines = BuildMockLine(breweryCode);
SelectList pLine = new SelectList(breweryCode, "LineNumber", "Descriptions", 0);
return Json(pLine);
}
Index.cshtml:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript">
function GetLine(_breweryCode) {
var url = '/Report/GetLine/';
$.ajax({
url: url,
data: { breweryCode: _breweryCode },
cache: false,
type: "POST",
success: function (data) {
alert('called');
var markup = '<option value="0">Select Line</options>';
for (var i = 0; i < data.length; i++) {
markup += '<option value="' + data[i].Value + '">' + data[i].Text + '</options';
}
$('#LineSelect').html(markup).show();
},
error: function (response) {
alert('fail' + ' ' + _breweryCode);
}
});
}
</script>
<div id="report-description">
#using (Html.BeginForm("Index", "Report", FormMethod.Post))
{
#Html.DropDownList("BreweryCode", (SelectList)ViewBag.Breweries, "Select Brewery", new { #class = "ui-select", #ID = "BrewerySelect", #onchange = "javascript:GetLine(this.Value);" })
<select class="ui-select" id="LineSelect" name="ReportSelect">
</select>
}
In your #onchange attribute, change this.Value to this.value
Try add
[HttpPost]
public ActionResult GetLine(string breweryCode)
{
List<PackagingLine> packagingLines = BuildMockLine(breweryCode);
SelectList pLine = new SelectList(breweryCode, "LineNumber", "Descriptions", 0);
return Json(pLine);
}
so GetLine can be able to process POST request
Please add datatype as well:
dataType: 'html', or dataType: 'json'
and add http method in a controller
[HttpPost]
public ActionResult GetLine(string breweryCode)
{
}
Also, make sure whether value _breweryCode is coming in below function
function GetLine(_breweryCode)
{
}
Take below code as sample
$.ajax({
type: "POST",
url: your url,
dataType: 'json',
data: JSON.stringify({ id: '2' }),
contentType: "application/json; charset=utf-8",
success: function (data) {
alert('hello');
}
});

Categories

Resources