Dropdown not filling when attempting to bind with ajax and controller action - javascript

I am trying to fill a dropdown using ajax and a controller action, but nothing seems to be happening when I click the button that triggers the action:
Ajax:
$.ajax({
url: '#Url.Action("GetBranch", "Report")',
type: "GET",
success: function (result) {
$("#dropdown2").append('<option value=' + result.BranchId + '>' + result.BranchName + '</option>');
}
});
Controller Action:
public ActionResult GetBranch()
{
var branch = new Branch();
var branchId = branch.BranchId;
var branchName = branch.BranchName;
return Json(new[]
{
new {Id = branchId, Value = branchName}
}, JsonRequestBehavior.AllowGet);
}
This is a practice I am not too familiar with so there could be something obvious missing. None of the answers here have been able to help me because I am trying to bind to an existing <select>; not a #DropdownListFor
It seems that the controller action is not getting hit with the ajax call, so nothing is getting returned.
Thanks for your help!

public JsonResult GetBranch()
{
var branch = new Branch();
var branchs = new List<Branch>();
var branchId = "Branch01"; //If only your branch id datatype is string
branch.branchId = branchId;
var branchName = "Name of Branch";//Name you want to give for your branch
branch.branchName = branchName;
branchs.Add(branch);
return Json(branchs.Select(t => new {Text = t.branchName, Value = t.branchId}), JsonRequestBehavior.AllowGet);
}

Related

MVC Controller is not receiving the values that comes from the Ajax /Javascript script

I debugged the JS and Ajax code with console.log. I can see that what I entered into the textbox, is displayed in the console. However, when these values are supposed to send to the controller, they are empty or null when I hover over the tbl_stuff List. Not sure where I am making a mistake.
Here is the JS:
$("body").on("click", "#btnSave", function () {
var table = $("table tbody");
var array= new Array();
table.find('tr').each(function (i) {
var $tds = $(this).find('td'),
Amount = $(this).find('.val').val();
valuestoupdate = { Amount: amount };
array.push(valuestoupdate);
});
$.ajax({
type: "POST",
url: "#Url.Action("StuffAction","Home")",
data: JSON.stringify(array),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) saved.");
}
});
Here is the controller action:
public JsonResult StuffAction(List<tbl_Stuff> stuffs)
{
int getID = (int)TempData["id"];
TempData.Keep();
var GetData = _context.tbl_Detail.Where(x => x.detId == getID).FirstOrDefault();
if (GetData != null)
{
foreach (tbl_Stuff moreThings in stuffs)
{
tbl_Stuff stuff = new tbl_Stuff();
stuff.Amount = moreThings.Amount;
_context.tbl_Stuff.Add(stuff);
}
}
int insertedRecords = _context.SaveChanges();
return Json(insertedRecords);
}
I get an error saying that moreThings.Amount is empty. But during debugging, the JS code gets the value entered into the textbox.
The .Net routing can't match the request
change the action signature to public JsonResult StuffAction(List< string > stuffs)
or in your ajax call change the array to an array of objects matching the properties of tbl_Stuff

Why is the Ajax call not being hit?

I am trying to apply a filter to data that is being displayed on a map but for some reason, the Ajax call that I have set up is not being executed. I can reach the console.log line in the view but anything after that in the Ajax call is never executed. This is being done in ASP.NET MVC.
I have similar Ajax calls in this project from other developers that function in a similar manner. I have tried to restructure my code to work in a similar manner, but with no success. The other developers have no idea what is going on either.
C# in the controller
[HttpPost]
public ActionResult MapFilter(string filterLake, bool filterPets)
{
var filteredProperties = db.Properties.Include(a => a.PropertyCategory).Where(b => b.Status == true).Select(x => new { x.PropertyName, x.PropertyId, x.RatePerNight, x.RatePerWeek, x.MarketingTitle, x.Latitude, x.Longitude, x.Pets, x.PropertyCategory.PropertyCategoryName });
if (filterLake != "")
filteredProperties = filteredProperties.Where(a => a.PropertyCategoryName == filterLake);
if (filterPets != true)
filteredProperties = filteredProperties.Where(a => a.Pets == filterPets);
var jsonProperties = JsonConvert.SerializeObject(filteredProperties);
return new JsonResult()
{
Data = jsonProperties,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
JavaScript & Ajax in the View
var filterLake, filterPets;
var btnApplyFilters = document.getElementById("applyFilters");
var filterLakeNode = document.getElementById("filterLake");
var filterPetsNode = document.getElementById("filterPets");
$(document).ready(function () {
btnApplyFilters.onclick = function () {
filterLake = filterLakeNode.options[filterLakeNode.selectedIndex].value;
filterPets = filterPetsNode.options[filterPetsNode.selectedIndex].value;
console.log("Lake:|" + filterLake + "| Pets:|" + filterPets + "|");
$.ajax({
url: "/Estates/MapFilter",
type: "Post",
data: {
"filterLake": filterLake,
"filterPets": filterPets
},
success: function (result) {
filteredMapData = result;
console.log("Result = " + result);
loadMapMarkers(true)
}
});
};
})
When I run the program on localhost, I am able to reach the
console.log("Lake:|" + filterLake + "| Pets:|" + filterPets + "|");
line with no issues. Anything after does not run.
You need check filterPets value, it must be true/false then model binder can map with bool type.
With primitive type (bool, int, float) you should use nullable type bool? for preventing case the value incorrect format.
[HttpPost]
public ActionResult MapFilter(string filterLake, bool? filterPets)
{
}
With this paramter if filterPets has wrong value, it will be null.

AJAX returns correct values from array except ID

I have this controller:
[HttpGet]
public JsonResult GetEvents() {
//var project = _context.Project.SingleOrDefault();
var events = _context.Project.Select(s => new {
ID = s.ID,
onSite = s.OnSite,
onSiteTill = s.OnSiteTill,
Number = s.Number,
Type = s.Type,
})
.ToList();
return Json(events);
}
When I break the code I got correct values in arrays (int,date,date,string,string)
But when I call data AJAX style I get all values except ID, which is on alert out as undefined.
$(document).ready(function () {
var events = [];
var now = moment();
var nextMonth = now.clone().add(1, 'month');
$.ajax({
type: "GET",
url: "/home/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
alert(v.ID);
events.push({
Description: ("Number: " + v.Number + ", Type: " + v.Type).link("Projects/Edit/" + v.ID),
start: moment(v.onSite),
// add one day due to excluding end date in callendar
end: v.onSiteTill != null ? moment(v.onSiteTill).add('days', 1) : null,
,
allDay: true
});
})......
Its driving me crazy, I tried to change int to string in controler still getting undefined, also put ID = s.ID as comment and it did not even make any difference (of course the data was not in array).
Could you please help?
Marek

How to pass dictionary from ajax to controller [duplicate]

I am wanting to pass a dictionary of type <int,int> to my controller via an Ajax post.
The main reason here is the post may have between 1-3 key value pairs here (none of these values are known at compile time) and in the future it may go up to 5.
Also in the post I have to pass in some other data, such as Id and name, which all works as normal.
How would I construct this dictionay in the javascript then send it via the JQuery post and finally receive it on the controller to process?
Edit 2:
I have decided to just solve this with a post for each value instead of trying to pass a dictionary.
EDIT:
Here is my source for the function so you can see what I am trying:
function BindAddMenuItem() {
$(".AddMenuItem").click(function (e) {
e.preventDefault();
//get header id from link by removing addmenuitem from this.id
var currentId = $(this).attr("id").replace("AddMenuItem", "");
//get itemnumber, itemname, itemdetails from textboxes with same header id
var restaurantId = jQuery.trim($("#RestaurantId").val());
var itemNumber = jQuery.trim($("#ItemNumber" + currentId).val());
var itemName = jQuery.trim($("#ItemName" + currentId).val());
var itemDetails = jQuery.trim($("#ItemDetails" + currentId).val());
var costs = new Object();
//select all textboxes with class "Header" + currentId
$(".Header" + currentId).each(function (i) {
var optionId = $(this).attr("id").replace("Option", "");
costs[optionId] = $(this).val();
});
$.ajax(
{
type: "POST",
url: "/Menu/AddMenuItem",
data: "reastaurantId=" + restaurantId + "&menuHeaderId=" + currentId + "&itemNumber=" + itemNumber + "&itemName=" + itemName + "&itemDetails=" + itemDetails + "&costs=" + costs,
dataType: "html",
success: function (result) {
var domElement = $(result);
$("#MenuContainer").replaceWith(domElement);
var newNum = parseInt(itemNumber) + 1;
$("#ItemNumber" + currentId).val(newNum);
BindAllBehaviours();
}
});
});
}
Something like (javascript)
dict = new Object();
dict['12'] = 5;
dict['13'] = 6;
dict['1000'] = 21;
dict['9'] = 13;
dict['13'] = 48;
$.post('/client.mvc/mypostaction/', { myDictionary: dict });
You can then post the dict object to your controller using a Dictionary<int, int> as property type.
ActionResult MyPostAction(Dictionary<string, int> myDictionary)
edit from author's code second time:
The following works for me, when having a Dictionary<string, int> kvPairs. <int, int> isn't going to work after all.
Make your post like:
var dict = new Object();
dict['13'] = 9;
dict['14'] = 10;
dict['2'] = 5;
$.post('controller.mvc/Test', { 'kvPairs': dict }, function(obj) { $('#output').html(obj.Count); });
JavaScript object / dictionary has to be passed as a list of key-value pairs to ASP.NET MVC controller when Dictionary<TKey, TValue> is expected. Example:
If you have a dictionary like this:
public Dictionary<string, decimal?> SomeMapping { get; set; }
then you have to use something like this in your JavaScript:
var sourceMapping = { a: 1, b: 1.5, c: null };
var SomeMapping = [];
for (var key in sourceMapping) {
if (sourceMapping.hasOwnProperty(key)) {
SomeMapping.push({ Key: key, Value: sourceMapping[key] });
}
}
I've used this approach in asynchronous POST request (sent using jQuery) that had content type set to 'application/json' (this may or may not be important in your case).
Client (JavaScript):
var dict = new Object();
dict.Key1 = "Value1"
dict.Key2 = "Value2"
$.post('/YourController/YourAction/', dict);
NOTE: The "dict" objects gets serialized behind the scenes before being sent to your action.
Server:
public ActionResult YourAction()
{
string postData = string.Empty;
using (StreamReader sr = new StreamReader(Request.InputStream))
{
postData = sr.ReadToEnd();
}
//Load post data into JObject (Newtonsoft.Json)
JObject o = JObject.Parse(postData);
//Extract each key/val
string val1 = (string)o["Key1"];
//Do whatever....
}
None of these worked for me except for mczers, but he doesn't show all the steps, and makes it difficult when you're trying to remember how you set up an ajax request. So I wanted to put everything that actually just works. First, in JavaScript:
var validDict = new Array();
validDict[0] = { key: 1, value: 4 }
validDict[1] = { key: 42, value: 5}
var path = "#Url.Action("ControllerName", "ActionName")";
$.ajax({
url: path,
type: "POST",
data: JSON.stringify(validDict),
contentType: "application/json; charset=utf-8",
async:false,
success: function(status, xhr)
{
alert(status);
},
error: function(xhr, status, error)
{
alert(error);
}});
Then in your controller:
[HttpPost]
public ActionResult ActionName(Dictionary<int, int> validDict)
{
// doStuff();
return Content("Success");
}
A dictionary of the kind IDictionary<string, string> on server side can be posted from javascript like
{"Key1": "Value1", "Key2": "Value2"}
on the Server Side in ASP.NET Web API
[HttpPost]
public IHttpActionResult([FromBody]IDictionary<string, string> requestParam){
}
Above example is for an Http POST with the Json data in the Body
For passing a Dictionary I found the following working answer:
submitting-a-dictionary-to-an-asp-net-mvc-action
#model WebApplication3.Controllers.ExampleViewModel #{ ViewBag.Title = "New";
var first = Guid.NewGuid(); var second = Guid.NewGuid(); }
<h2>New</h2>
#using (Html.BeginForm(new { action = "create", controller = "home" })) {
foreach (var kvp in Model.Values) {
<p>
<input type="text" name="Model.Values[#first].Key" value="#kvp.Key" />
<input type="text" name="Model.Values[#first].Value" value="#kvp.Value" />
<input type="hidden" name="Model.Values.Index" value="#first" />
</p>
}
you have to generate A Guid for the dictionary index, and you have to create 3 inputs, one for the Key, one for the Value and one for the Index of the Dictionary
Also I have submited using Jquery with the following:
$('form#frmFormId').submit(function (e) {
e.preventDefault();
var formData = new FormData(this);
//debugger;
$('#cover-spin').show(100);
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData,
processData: false,
contentType: false
}
);
return false;
});

Pass value from javascript to MVC controller

In my MVC web application I have a button on the LyncUser Create view that needs to get the value of 'AddressBookNBo' and pass this to the findEmpSurname in my Staff controller. This action then uses the AddressBookNo to retrieve the Surname value from the Staff model. The Surname value is then used to automaticatically populate the Surname value on the LyncUser create view.
When I debug the app and put a stop on the controller action I can see that AddressBookNo is null. Can you advise what I am doing wrong here please.
findEmpSurname action in Staff...
[HttpGet]
public JsonResult FindEmpSurname(int? AddressBookNo)
{
var staffDB = new StaffEntities();
var surnames = staffDB.Staff.AsQueryable();
if (AddressBookNo != null)
{
surnames = surnames.Where(p => p.AddressBookNo == AddressBookNo);
}
return Json(surnames.Select(p => new { Surname = p.Surname }), JsonRequestBehavior.AllowGet);
}
Telerik Kendo UI MVC button that calls the PopTextBox javascript when clicked.
#(Html.Kendo().Button()
.Name("findEmpSurname")
.Content("Lookup Surname")
.HtmlAttributes(new { type = "button" })
.Events(ev => ev.Click("PopTextBox"))
)
PopTextBox javascript that gets the value of AddressBookNo, passed this to the controller, and uses the returned value to set the Surname value.
function PopTextBox()
{
var data = { AddressBookNo: $("AddressBookNo")[0].value };
$.ajax({
url: '#Url.Action("FindEmpSurname","Staff")',
type: 'GET',
dataType: 'json',
data: data,
cache: false,
success: function (result) {
var surnameTextbox = document.getElementById('Surname');
surnameTextbox.value = result;
}
})
}

Categories