Fill DropDownList with JsonData - c#

I haven't worked on Json before,its my first time and as expected I stucked at a point where I want to fill the DropDown with the JsonData.
Here What I am doing is I have an Xml which I am converting in Json like:
string xml = "<Root><Name>A</Name><Name>B</Name><Name>C</Name></Root>";
Then doing this to convert it into JsonString:
XmlDocument doc = new XmlDocument();
doc.LoadXml(Xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
Currently my View is like:
<div>
<input type="button" value="work" name="work" id="idwork" />
</div>
#Html.DropDownListFor(x => x.Name, new SelectList(Enumerable.Empty<SelectListItem>()), new {id="ddl_items" })
Script:
var ddl = $('#ddl_items');
$('#idwork').on('click', function () {
$.ajax({
url: url,
data: {},
type: 'post',
contentType: 'application/json; charset=utf-8',
success: function (myJSONdata) {
$(myJSONdata.Name).each(function () {
ddl.append(
$('<option/>', {
value: this.ReworkTunnelName
}).html(this.Nome)
..
..
});
Now what I want to do is Fill the Dropdown with Names with the help of this JsonData.
please help

$.each(myJSONdata, function ()
{
ddl.append($("<option></option>").attr("value", this.ReworkTunnelName).text(this.Nome));
});
Edit
$.each(myJSONdata, function ()
{
ddl.append($("<option></option>").attr("value", this.ReworkTunnelName).attr("text",this.Nome));
});
$.each(myJSONdata.Root, function ()
{
ddl.append($("<option></option>").attr("text", this.ReworkTunnelName));
});

You can create a new javascript function and pass the dropdown id and json data as parameters in it.
Then you can parse json data as per your data structure. Further run a loop and add items in the select element.

you can use getJSON method in jQuery :
$.getJSON("ActionMethodName", "", function (data) {
$(data).each(function () {
$("<option>").val(this.ReworkTunnelName)
.text(this.Nome)
.appendTo("#ddl_items");
});
});
HTML :
<select id="ddl_items">
<option></option>
</select>

I end up doing this and this is working Fine..
$('#idRework').on('click', function () {
$.ajax({
url: url,
data: {},
type: 'post',
contentType: 'application/json; charset=utf-8',
success: function (myJSONdata) {
var obj = jQuery.parseJSON(myJSONdata);
$.each(obj.Root.ReworkTunnelName, function (index, itemData) {
ddl.append($('<option></option>').val(itemData).html(itemData));
});
}
});
});

Try this
$.each(myJSONdata, function (index, item) {
$('#ddl_items').get(0).options[$('#ddl_items').get(0).options.length] = new Option(item.Text, item.Value);
});

Related

grab value from checkboxes and post as list to controller

Check the code bellow. I am doing post a list of ProductId to my controller and wanted to receive it with view model called- UpdateProductStatus. but the problem with my current code is: ajax post it to controller successfully but the UpdateProductStatus cant grab any value of ProductId. This always returns null. Whats wrong i am doing here? Possibly in ajax i am doing wrong i think. How can i fix this to receive all ProductId as a list form controller? Thanks in advance
Controller:
[HttpPost]
public IActionResult UpdateProductStatus([FromBody]List<UpdateProductStatus> UpdateProductStatus)
{
return Json("ok");
}
View Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BlexzWeb.ViewModels
{
public class UpdateProductStatus
{
public int ProductId { get; set; }
}
}
Jquery:
$('#btnActivate').on('click', function () {
var allSelectedProductId = [];
var allSelectedProductIdWithKey = [];
$('.chkItems:checked').each(function() {
allSelectedProductId.push($(this).val());
});
for (var _allSelectedProductId in allSelectedProductId) {
allSelectedProductIdWithKey.push('ProductId'+':'+_allSelectedProductId);
}
console.log(allSelectedProductIdWithKey);
//var things = JSON.stringify(allSelectedProductIdWithKey);
var things = JSON.stringify({ 'UpdateProductStatus': allSelectedProductIdWithKey });
console.log(things);
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Products/UpdateProductStatus',
data: things,
success: function () {
console.log('sssss');
},
failure: function (response) {
console.log('fffff');
}
});
Html:
<input type="checkbox" class="chkItems" value="1">
<input type="checkbox" class="chkItems" value="2">
<button id="btnActivate">Button</button>
Your current code is sending a payload like below for the ajax call.
{"UpdateProductStatus":["ProductId:0","ProductId:1"]}
Your action method argument is a list of UpdateProductStatus objects. So for model binding to work properly with your current action method parameter signature, your payload should be like below.
[{"ProductId":"1"},{"ProductId":"2"}]
There is no need to specify the parameter name. Just pass an array of items, each with a ProductId property and it's value.
var allSelectedProductIdWithKey = [];
$('.chkItems:checked').each(function () {
allSelectedProductIdWithKey.push({ ProductId: $(this).val() });
});
var things = JSON.stringify(allSelectedProductIdWithKey);
$.ajax({
contentType: 'application/json; charset=utf-8',
type: 'POST',
url: '/Products/AppendClientFilter',
data: things,
success: function (res) {
console.log('Successs', res);
},
failure: function (response) {
console.log('Error', response);
}
});
You can also remove the dataType in ajax call. jQuery ajax will guess the proper type from the response header and in your case you are going to return explicitly JSON.
To bind to your controller method, you need to send an array of objects containing a name/value pair for ProductId. To build your array of objects, use
$('#btnActivate').on('click', function () {
var allSelectedProductId = [];
$('.chkItems:checked').each(function() {
allSelectedProductId.push({ ProductId: $(this).val() });
});
var things = JSON.stringify({ UpdateProductStatus: allSelectedProductId });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Products/UpdateProductStatus',
data: things,
success: function () {
....
});
});

Fetching Cities dynamically in Asp.net HTML control

I have a HTML dropdown list for countries. Now I want to populate the City dropdown accordingly using ajax
<select class="form-control" id="ddCountry" runat="server" tabindex="8"></select>
<select class="form-control" id="ddCity" runat="server" tabindex="9"></select>
<script type="text/javascript">
$('#ddCountry').on('change', function () {
var storeData = { countryId: this.value }
$.ajax({
type: "POST",
url: "UserRegistration.aspx/GetCities",
data: JSON.stringify(storeData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("The data in list is "+data);
},
error: error
});
});
</script>
My method on .cs page is as follows:
[WebMethod]
public static List<CityBO> GetCities(string countryId)
{
//returning cities
}
The problem is I am able to fetch the data in GetCities method but not able to show it in the ddCity list because it is a HTML control and the method is static, so
ddCity.Items.AddRange(list_of_countries) is not working as ddCity is not being recognized in static method. Please tell how to fill the dropdown list.
You cannot access controls in static method. You need to return list of cities from webmethod and fill dropdown using javascript.In success method of ajax write code like this.
success: function (data) {
fillDropDown(data.d);
}
function fillDropDown(data){
var html = "";
for (var i = 0; i < data.length; i++)
{
html += "<option value='" + data[i].ValueField+ "'>" +
data[i].TextField+ "</option>";
}
$("select[id$=ddlCity]").html(html);
}
You can use ajax success function given below.
success: function (data)
{
var lankanListArray = JSON.parse(data.d);
// running a loop
$.each(lankanListArray, function (index, value)
{
$("#ddlCity").append($("<option></option>").val(this.name).html(this.value));
});
}

Get url parameters

Here is what I am trying to do. I'm trying to pass the drop down selected value to my controller.
I have a drop down menu like this:
#Html.DropDownList("divs", null, "--Select--", new {id="divs", onchange="SelectedIndexChanged(this.value);" })
#section Scripts
{
<script>
function SelectedIndexChanged(divs) {
document.getElementById('divs').href =
'/Controllers/MyFunction?divs=' + divs;
}
</script>
}
in my controller, I am trying to get the value divs:
public MyFunction (string divs)
{
string type = Request.QueryString["divs"];
MessageBox.Show(type); //this is empty
}
Typing this from my head compiler so it might not be quite right but should get you closer.
#Html.DropDownList("divs", null, "--Select--", new { id="divs"})
#section Scripts
{
<script>
$(function() {
$("#divs").change(function() {
val selected = $(this).find(":selected").val();
$.ajax({
type: 'POST',
url: '#Url.Action("MyFunction", "Controller", new { divs = selected })',
dataType: 'json',
});
});
});
</script>
}
In your controller:
public ActionResult MyFunction (string divs)
{
...
}
I believe that this is what you're trying to do. It's not a complete solution, you have to work it out.
Note: I'm using jQuery for the javascript part.
Action:
public JsonResult MyFunction (string divs)
{
return Json(divs, JsonRequestBehavior.AllowGet);
}
View:
$(function() {
$("#divs").changed(function() {
$.ajax({
url: '/controllers/myfunction'
, cache: false
, type: 'GET'
, dataType: 'json'
, data: { divs = $(this).val() }
}).done(function (data) {
alert(data);
});
});
});
You can remove that javascript binding from the dropdown declaration.

use json data created via javascript with ajax.actionlink

I want to be able to post json data that was created via a javascript function through the Ajax.ActionLink helper.
I am able to accomplish this through straight jQuery code, but I am going to be doing this in a lot of places and wanted to see if there was a more efficient way to do it within MVC.
Working jQuery code:
$(function () {
$("#delete-selected").click(function () {
var ids= getSelected('ItemGrid'); //this returns a string[]
var postData = { Ids: courseIds };
var url = '/Home/DeleteSelected';
$.ajax({
url: url,
traditional: true,
type: "Post",
dataType: 'json',
data: postData
});
});
});
Write a script that uses unobtrusive JavaScript hooks like data- attributes to store the settings.
HTML:
<div data-ajax-url='/Home/DeleteSelected'
data-ajax-post-data='{function name or json content}'>
....
</div>
JQuery Plugin
$(document).on("click","[data-ajax-url]", function(){
var postData = $(this).data("ajax-post-data");
var url = $(this).data("ajax-url");
$.ajax({
url: url,
traditional: true,
type: "Post",
dataType: 'json',
data: postData
});
}
If you are doing an ajax call and want to update html with MVC, I would normally return Partial View from my call.Then update the html of the current holder with the result
Server Side
public ActionResult DeleteSelected(int[] Ids)
{
//do something
MyModel model = new Model(); //create object with new data
return Partial("_PartialViewName", model);
}
Javascript
$("#delete-selected").click(function () {
var ids= getSelected('ItemGrid'); //this returns a string[]
var postData = { Ids: courseIds };
var url = '/Home/DeleteSelected';
$.ajax({
url: url,
traditional: true,
type: "Post",
dataType: 'html',
data: postData
success: function(result){
$('#MyPartialViewContainer').html(result);
}
});
});

why does this ajax error happen when I post html with stringify

Why does this ajax error happen when I try post html in the string with stringify.
It looks like the stringify escapes the charactors automatically.
do I have to escape? thanks
var s;
//s = "my test test"; //if I post this it works
s = "my test test<br />"; //if I post this it break when I add the html
var a = { "myText": JSON.stringify(s) };
$.ajax({
type: "POST",
url: "test.aspx",
data: a,
success: function (data) {
//pass
},
error: function () {
alert("error");
}
});
then on the page load I'm trying to read the posted data with
HttpContext.Current.Request.Form("myText")
Try this:
var s = "my test test<br />",
a = { "myText": s };
a = JSON.stringify(a)
$.ajax({
type: "POST",
url: "test.aspx",
data: a,
success: function (data) {
//pass
},
error: function () {
alert("error");
}
});
You don't need to call JSON.stringify().
JSON.stringify is intended to serialize the object to JSON string, but you're passing a string to it and it's wrong.
Just pass the object with $.ajax() call:
var s = "my test test<br />";
.ajax({
type: "POST",
url: "test.aspx",
data: {
myText: s
},
success: function (data) {
//pass
},
error: function () {
alert("error");
}
});
Also jQuery documentation:
The data option can contain either a query string of the form
key1=value1&key2=value2, or a map of the form {key1: 'value1', key2:
'value2'}.
So in our particular example we used a "map" of the form, namely JavaScript object.

Categories

Resources