When making an ajax request, how can I use a jquery variable in the url parameter that uses c#? - c#

Here is the code that I have:
var selectedFacility = $("#Facility").val();
$.ajax({
type: "Post",
url: "#Url.Action("GetLocations", "Item", new { Facility = "selectedFacility goes here"})",
dataType: 'json',
success: function (data) {
for (var i = 0; i < data.length; i++) {
$('#Location').append('<option value="' + data[i].Value + '">' + data[i].Text + '</option > ');
}
}
});
Controller action:
public JsonResult GetLocations(string facility) {
var Locations = new List<SelectListItem>{};
Locations.AddRange(db.Locations.Where(l => l.Facility == "LAT").ToList().Select(l => new SelectListItem {
Text = l.Name,
Value = l.ID.ToString()
}));
return Json(Locations, JsonRequestBehavior.AllowGet);
}
This is the line that I need to use the variable on:
new { Facility = "selectedFacility goes here"})",
I might be missing something obvious, but I need to use the selectedFacility jquery variable in the Url.Action() parameters. Is there a way that this can be done?

I think you can't use $("#Facility").val(); parameter in the Url.Action() method.
You are using http POST I think you can try to set the ajax data object to be the parameter.
var selectedFacility = $("#Facility").val();
$.ajax({
type: "Post",
url: '#Url.Action("GetLocations", "Item")',
data: { Facility: selectedFacility },
dataType: 'json',
success: function (data) {
for (var i = 0; i < data.length; i++) {
$('#Location').append('<option value="' + data[i].Value + '">' + data[i].Text + '</option > ');
}
}
});

Related

Displaying a list in a view from data passed from a controller

I'm passing a list in JSON format from my controller, the data from the list is not being displayed in the view for some reason.
Here is the data being passed in controller:
[HttpPost]
public ActionResult GetIndustryCat(string Country)
{ var dataContext = MvcApplication.GetDataContext();
var Location = dataContext.Locations.Single(c => c.Location_Name == Country);
var IndustryCat = dataContext.IndustryCategories.Where(c => c.Location_ID == Location.Location_ID).ToList();
return Json(new {Cat = IndustryCat.Select(c => c.IndustryCategory_Name) });
}
Here is the view:
</select>
<script>
$("#selectindustrycat").hide();
$("select")
.change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$.ajax({
url: "GetIndustryCat",
type: "POST",
data: { Country: str },
success: function (data) {
}
}).done(function (data) {
for (var i = 0; i < data.length; i++) {
$("#selectindustrycat").append('<option value=' + i + '>' + i + '</option>');
}
$("#selectindustrycat").show();
});
});
</script>
The selection option list displays but it has no data in it.
You need change from data to data.Cat
for (var i = 0; i < data.Cat.length; i++) {
$("#selectindustrycat").append('<option value=' + i + '>' + i + '</option>');
}

Jquery returns value “undefined” .net core

I want to populate second dropdown from first one.
It all works but city names and values just returns "undefined". *Number of cities returns correct but the name and value are always "undefined". *
Controller:
[HttpPost]
public ActionResult getCityJson(string stateId)
{
int _stateid = Convert.ToInt32(stateId);
List<Cities> objcity = new List<Cities>();
objcity = _db.Cities.Where(m => m.stateID == _stateid).ToList();
SelectList obgcity = new SelectList(objcity, "CityID", "CityName", 0);
return Json(obgcity);
}
View Page:
$("#istateid").change(function () {
var id = $("#istateid").val();
$.ajax({
url: '#Url.Action("getCityJson", "Home")',
data: { stateId: id },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#icityid").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
I also tried Public JsonResult and return JsonResult and Public Selectlist and return SelectList but none of them worked.
And I also tried this:
$("#istateid").change(function () {
$.ajax({
type: "POST",
url: '#Url.Action("getCityJson", "Home")',
data: { stateId: $("#istateid > option:selected").attr("value") },
success: function (data) {
var items = [];
items.push("<option>--Choose Your City--</option>");
$.each(data, function () {
items.push("<option value=" + this.Value + ">" + this.Text + "</option>");
});
$("#icityid").html(items.join(' '));
}
}) });
I recieve this in browser:
(TypeError: data[x] is undefined.)
$("#istateid").change(function () {
var id = $("#istateid").val();
$.ajax({
url: '/Home/getCityJson',
data: { stateId: id },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++)
{ markup += "<option value=" + data[x].CityID + ">" + data[x].CityName + "</option>"; }
$("#icityid").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
<option value="0">Select City</option>
<option value="undefined">undefined</option>
<option value="undefined">undefined</option>
<option value="undefined">undefined</option>
Solved:
items.push("<option value=" + this.value + ">" + this.text + "</option>");
Value and text camel cased.
Special thanks to #agua from mars
Other codes I tried:
$("#istateid").change(function () {
$.ajax({
type: "POST",
url: '#Url.Action("getCityJson", "Admin")',
data: { stateId: $("#istateid > option:selected").attr("value") },
success: function (data) {
var items = [];
items.push("<option>--Choose Your Area--</option>");
$.each(data, function () {
items.push("<option value=" + this.Value + ">" + this.Text + "</option>");
});
$("#icityid").html(items.join(' '));
}
})
});
Controller:
[HttpPost]
public JsonResult getCityJson(string stateId, string selectCityId = null)
{
return Json(getCity(stateId, selectCityId));
}
public SelectList getCity(string stateId, string selectCityId = null)
{
IEnumerable<SelectListItem> cityList = new List<SelectListItem>();
if (!string.IsNullOrEmpty(stateId))
{
int _stateId = Convert.ToInt32(stateId);
cityList = (from m in db.Cities where m.StateID == _stateId select m).AsEnumerable().Select(m => new SelectListItem() { Text = m.CityName, Value = m.CityID.ToString() });
}
return new SelectList(cityList, "Value", "Text", selectCityId);
}
try this:
success: function (data) {
var response=JSON.parse(data);
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < response.length; x++)
{ markup += "<option value=" + response[x].CityID + ">" + response[x].CityName + "</option>"; }
$("#icityid").html(markup).show();
},

Parse list of object passed by ajax request in webmethod

I'm making an ajax request to save data, multiple record can be save by one request.
this is my javascript function
function savePartRequestMail() { // send part request mail
var textPN = new Array();
var textPD = new Array();
var textPQ = new Array();
$('.txtPn').each(function () {
var tvalue = $(this).val();
if (tvalue != "") {
textPN.push(tvalue);
}
});
$('.txtPD').each(function () {
var tvalue = $(this).val();
if (tvalue != "") {
textPD.push(tvalue);
}
});
$('.txtPQ').each(function () {
var tvalue = $(this).val();
if (tvalue != "") {
textPQ.push(tvalue);
}
});
var PartRequest = {};
PartRequest.PartNumber = textPN;
PartRequest.PartDetail = textPD;
PartRequest.PartQty = textPQ;
$.ajax({
type: 'POST',
url: 'wom_service.asmx/sendPartRequestMail',
// data: '{"pno" : "' + textPN + '", "pdetail" : "' + textPD + '","pQTY" : "' + textPQ + '", ,"oid" : "' + oid + '"}',
data: JSON.stringify({ plist: PartRequest, oid: oid }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert('e-mail sent successfully');
$('#pRequestPopup').simpledialog2('close');
},
error: function (result) {
alert("Could not complete request");
}
});
}
passing data as
{"plist":{"PartNumber":["sdfasf","dsf","sf"],"PartDetail":["dsf","sfdsf","sf"],"PartQty":["sdf","sf","sf"]},"oid":"100003"}
Webmethod
public string sendPartRequestMail(PartRequest plist, int oid)
{
// here i want to get each list item
return "w";
}
How can i get each item like each item from "PartNumber":["sdfasf","dsf","sf"], and so on, am I working on wrong procedure

JQuery.Ajax and MVC4

I have a need to call a method on my controller to return a complex type using the JQuery.Ajax method.
function CallMethodTest(Id) {
//alert(Id);
$.ajax({
type: 'POST',
url: '/MyController/MyMethod',
dataType: "json",
contentType: "application/json; charset=utf-8",
//data: "{'Id': '" + Id + "'}",
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
[System.Web.Services.WebMethod]
public string MyMethod()
{
return "ABC"; // Gives me the error on the first alert of "200" and the second alert "Syntax Error: Invalid Character"
return "1"; // Works fine
}
As the code explains, if I return an integer (as a string) the return works and I alert "1", however, If I try and return any alpha characters I get the alerts shown in the comments of MyMethod.
From your code, it looks as though you are returning the value from your Controller url: "/MyController/MyMethod"
If you are returning the value from your controller, then get rid of the [System.Web.Services.WebMethod] code and replace it with this ActionResult
[HttpPost]
public ActionResult MyMethod(){
return Json("ABC");
}
Also, if you are ever going to call a method in your controller via GET then use
public ActionResult MyMethod(){
return Json("ABC", JsonRequestBehavior.AllowGet);
}
In View You use the following code,
function ItemCapacity() {
$.ajax({
type: "POST",
url: '#Url.Action("ItemCapacityList", "SalesDept")',
data: { 'itemCategoryId': itemCategoryIds },
dataType: 'json',
cache: false,
success: function (data) {
var capacityCounter = 0;
var capacitySelected = "";
for (var i = 0; i < rowsCount; i++) {
var tr = $("#gvSpareSetItemsDetails tbody tr:eq(" + i + ")");
var categoryId = $(tr).find('td:eq(5)').text();
var isSelectOrNot = $(tr).find('td:eq(1)').find('select');
if (isSelectOrNot.is('select')) {
$.map(data, function (item) {
if (categoryId == item.ItemCategoryID) {
isSelectOrNot.get(0).options[isSelectOrNot.get(0).options.length] = new Option(item.CapacityDescription, item.ItemCapacityID);
capacityCounter = capacityCounter + 1;
capacitySelected = item.ItemCapacityID;
}
});
if (capacityCounter == 1) {
isSelectOrNot.val(capacitySelected);
}
capacityCounter = 0;
capacitySelected = "";
}
}
},
error: function () { alert("Connection Failed. Please Try Again"); }
});
}
}
In the Controller Use the following Code,
public JsonResult ItemCapacityList(string itemCategoryId)
{
List<ItemCapacity> lsItemCapacity = new List<ItemCapacity>();
string[] itemCategory = itemCategoryId.Split('#');
int itemCategoryLength = itemCategory.Length, rowCount = 0;
string itemCategoryIds = string.Empty;
for (rowCount = 0; rowCount < itemCategoryLength; rowCount++)
{
itemCategoryIds += "'" + itemCategory[rowCount].Trim() + "',";
}
itemCategoryIds = itemCategoryIds.Remove(itemCategoryIds.Length - 1);
lsItemCapacity = salesDal.ReadItemCapacityByCategoryId(itemCategoryIds);
return new JsonResult { Data = lsItemCapacity };
}

returning List<string> from JSON call in Jquery has undefined length

I am making a call to a webservice from jquery and trying to return an List (I have also tried a string[]). When I get the results back I can see it holds an array with the values I need, but I can not iterate through them in Javascript because there is no length value.
my C# Webservice is as follows:
[WebMethod]
public string[] GetMultiChoiceOptions(int keyId)
{
string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["OBConnectionString"].ConnectionString;
SitesUtil db = new SitesUtil(connectionString);
List<MultiChoiceOption> keys = db.GetMultiChoiceOptions(keyId, 1); //TO DO CHANGE THIS TO REAL USERID
return keys.Select(a => a.OptionValue).ToArray();
}
and My Jquery/javscript call is as follows:
function GetKeys(keyid) {
var pageUrl = '<%=ResolveUrl("~/WebService/UpdateDatabase.asmx")%>'
$.ajax({
type: "POST",
url: pageUrl + "/GetMultiChoiceOptions",
data: '{keyId:' + keyid + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: GetKeysSuccessCall,
error: OnErrorCall
});
}
function GetKeysSuccessCall(response) {
/* TO DO */
var i = 0;
for (i =0; i < response.length; i++) {
$("#popupList").append('<li>' + response[i] + '</li>');
}
}
I'm not sure how I deal with an array without a length in javascript?
First, use Google Console. Best and helpful.
To see what you receive, use console.log(response); (instead of alert and do NOT use in IE because it doesn't know console)
try first of all
$.ajax({
type: "POST",
url: pageUrl + "/GetMultiChoiceOptions",
data: '{keyId:' + keyid + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response){
GetKeysSuccessCall(response);
},
error: function(msg) {
OnErrorCall(msg);
}
});
And one more :
function GetKeysSuccessCall(response) {
/* TO DO */
var i = 0;
for (i =0; i < response.length; i++) {
$("#popupList").append('<li>' + response[i] + '</li>');
}
}
repsonse must be instead of item
I think you should use first of all the JSONSerializer to send the rigth json structure to the client.
You should return only a string, which has the JSON format, and then it will work!
I cant explain why it works, but what I needed to do was get the response.d value....
So this was the solution in the end:
function GetKeysSuccessCall(response) {
/* TO DO */
var result = response.d;
var i;
for (i = 0; i < result.length; i++)
{
$("#popupList").append('<li>' + result[i] + '</li>');
}
}
(if someone can explain where the .d comes from?)
You can use the .each function like so
success: function (response) {
var options= response.d;
$.each(options, function (index, option) {
$("#popupList").append('<li>' + response[option] + '</li>');
});
},
or
function GetKeysSuccessCall(response) {
/* TO DO */
var i = 0;
for (i =0; i < response.d.length; i++) {
$("#popupList").append('<li>' + response.d[i] + '</li>');
}
}

Resources