jQuery Ajax call to controller - asp.net-mvc

I'm new to Ajax and I'm trying to disable a checkbox if certain items are selected in a dropdown. I need to pass in the mlaId to the GetMlaDeliveryType(int Id) method in the RecipientsController.cs.
I'm not exactly sure how to set up the ajax call in the javascript function checkMlaDeliveryType(mlaId).
// MLA Add disable express checkbox if delivery type is electronic
$('.AddSelectedMla').change(function () {
var deliveryType = checkMlaDeliveryType($('.AddSelectedMla').val());
// disable express option if delivery type is Electronic
if (deliveryType == "Mail") {
$(".mlaExpressIndicator").removeAttr("disabled");
}else{
$(".mlaExpressIndicator").attr('checked', false).attr("disabled", true);
}
})
// ajax call to get delivery type - "Mail" or "Electronic"
function checkMlaDeliveryType(mlaId)
{
$.ajax({
type: "GET",
url: "/Recipients/GetMlaDeliveryType/" ,
data: mlaId,
dataType: ,
success:
});
}
RecipientsController.cs
public string GetMlaDeliveryType(int Id)
{
var recipientOrchestrator = new RecipientsOrchestrator();
// Returns string "Electronic" or "Mail"
return recipientOrchestrator.GetMlaDeliveryTypeById(Id);
}
EDIT:
Here's how the final javascript looked that worked
// MLA Add disable express checkbox if delivery type is electronic
$('.AddSelectedMla').change(function () {
checkMlaDeliveryType($('.AddSelectedMla').val());
})
// ajax call to get delivery type - "Mail" or "Electronic"
function checkMlaDeliveryType(mlaId)
{
$.ajax({
type: 'GET',
url: '#Url.Action("GetMlaDeliveryType", "Recipients")',
data: { id: mlaId },
cache: false,
success: function (result) {
// disable express option if delivery type is Electronic
if (result == "Mail") {
$(".mlaExpressIndicator").removeAttr("disabled");
} else {
$(".mlaExpressIndicator").attr('checked', false).attr("disabled", true);
}
}
});
}

$.ajax({
type: 'GET',
url: '/Recipients/GetMlaDeliveryType',
data: { id: mlaId },
cache: false,
success: function(result) {
}
});
then fix your controller action so that it returns an ActionResult, not a string. JSON would be appropriate in your case:
public string GetMlaDeliveryType(int Id)
{
var recipientOrchestrator = new RecipientsOrchestrator();
// Returns string "Electronic" or "Mail"
return Json(
recipientOrchestrator.GetMlaDeliveryTypeById(Id),
JsonRequestBehavior.AllowGet
);
}
Now your success callback will directly be passed a javascript instance of your model. You don't need to specify any dataType parameters:
success: function(result) {
// TODO: use the result here to do whatever you need to do
}

Set data in the Ajax call so that its key matches the parameter on the controller (that is, Id):
data: { Id: mlaId },
Note also that it's a better practice to use #Url.Action(actionName, controllerName) to get an Action URL:
url: '#Url.Action("GetMlaDeliveryType", "Recipients")'

Related

How to send json object to the Controller Action method in MVC 4

I am trying to send my userid and password to my login Controller Action method.
//Login button click code
$("#btnLogin").click(function () {
var userCrdential = {
UserName: $("inputEmail3").val(),
Password: $("inputPassword3").val()
};
$.ajax({
type: "POST",
url: "/Home/Login",
content: "application/json; charset=utf-8",
dataType: "json",
data: userCrdential,
success: function (res) {
// alert("data is posted successfully");
if (res.success == true)
alert("data is posted successfully");
else {
// alert("Something went wrong. Please retry!");
}
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr.statusMessage);
}
});
});
and in my home Controller I have login Action method
[HttpPost]
[ActionName("Login")]
public ActionResult Login(User userCrdential)
{
string userIdtest = userCrdential.UserName;
string userPasswordtest = userCrdential.Password;
var result=false;
if (userIdtest != null && userPasswordtest != null)
{
result = true;
}
else
{
result = false;
}
return Json(result);
//return RedirectToAction("Index");
}
but my action method is not invoking...
You need to change content to contentType and call JSON.stringify on your data:
$.ajax({
type: "POST",
url: "/Home/Login",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(userCrdential),
...
});
See jQuery.ajax
Just change it from:
var userCrdential = {
UserName: $("inputEmail3").val(),
Password: $("inputPassword3").val()
};
to:
var userCrdential = "UserName=" + $("inputEmail3").val() + "&Password=" + $("inputPassword3").val();
all other things is ok in your code, but make sure your controller parameter having the same parameters passing here i.e. UserName and Password.
however you need to check user input before calling ajax.
You should never hard-code URLs in MVC.
Instead use #Url.Action.
url: ('#Url.Action("Login", "Home")',
userCrdential needs to be JSON encoded:
JSON.stringify(userCrdential)
Also, for the same of your sanity, please use the fail method.
$.ajax("url")
.done(function() {
alert("success");
})
.fail(function() {
alert("error");
})
One last note, success is deprecated as of jQuery 1.8; you should use done instead.

How to bind IDictionary data in a Webgrid

i have a ajax call which calls the ControllerName "Floor" and ActionMethod "GetHotelingList".i have a Dropdown list facility. when i select option from the Dropdownlist list the control goes to ajax call.based on selection value, the Webgrid must be displayed. #grdHoteling is Webgrid id.
$.ajax({
type: 'GET',
url: '/Floor/GetHotelingList',
cache: false,
contentType: 'application/html; charset=utf-8',
dataType: 'html',
data: { floorId: floorId },
success: function (data) {
debugger;
$("#grdHoteling").val(data);
//debugger;
//$("#grdHoteling").html(data);
},
complete: function () {
},
error: function () {
if (facilityName.indexOf('-') != -1) {
$('#floor').empty();
return;
}
else
alert("Error in generating hoteling information");
}
});
Here is the ActionMethod GetHotelingList value is paased floorId for some fileration.
public List<IDictionary> GetHotelingList(int floorId)
{
var model = new List<IDictionary>();
using (var context = new FloorContext())
{
try
{
model = ListHotelingByFloorId(context, floorId);
}
catch (Exception ex)
{
}
}
return model;}
On Success of the ajax call, when i check through debugger am getting data as "System.Collections.Generic.List`1[System.Collections.IDictionary]" and child cannot be evaluated.
kindly help...!
thanks...!

Send data from js to controller

I have this ajax:
function sendData() {
var question = (document.getElementById('question').value).toString();
var c = (document.getElementById('c').value).toString();
$.ajax({
url: '/Home/InsertData',
type: 'POST',
data: {question:question, c:c},
// data: {},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert('suc');
},
error: function (error) {
alert('error');
}
});
}
in my HomeController, I have the function:
[HttpPost]
public void InsertData(string question, string c)
//public void InsertData()
{
this.insertDataToCustomers(question, c);
}
when I run it, I got an error of:
POST http://localhost:2124/Home/InsertData 500 (Internal Server Error)
If I didn't ask for input values in InsertData function and didn't send data in the ajax, it works. why can't I send data to InsertData function?
p.s. There are values in question and c
thank you!
Remove this:
contentType: 'application/json; charset=utf-8',
You are not sending any JSON to the server, so this is an incorrect content type for the request. You are sending a application/x-www-form-urlencoded request.
So:
function sendData() {
var question = $('#question').val();
var c = $('#c').val();
$.ajax({
url: '/Home/InsertData',
type: 'POST',
data: { question: question, c: c },
success: function () {
alert('suc');
},
error: function (error) {
alert('error');
}
});
}
Another problem with your code is that you indicated dataType: 'json' which means that you expect the server to return JSON but your controller action doesn't return anything. It's just a void method. In ASP.NET MVC controller actions should return ActionResults. So if you want to return some JSON for example to indicate the status of the operation you could have this:
[HttpPost]
public ActionResult InsertData(string question, string c)
{
this.insertDataToCustomers(question, c);
return Json(new { success = true });
}
Of course you could return an arbitrary object which will be JSON serialized and you will be able to access it in your success AJAX callback.

.ajax get keep data keep coming null in controller

I am trying to use this following function to get some data.
function SaveData() {
var value = $('#tblRadio').find('input[type="radio"]:checked').val();
$.ajax({
type: "POST",
url: '/home/IsEmployeeVoted',
success: function (result) {
alert(result); // shows whole dom
if (parseInt(result) > 0) {
$('div.dvVoteWrapper').removeAttr('style');
$('div.popupArea').removeAttr('style');
}
else {
window.location = '/home/EmployeeVote?regoinID='+ value;
}
},
error: function () {
alert("Sorry, The requested property could not be found.");
}
});
}
The controller function:
public ActionResult EmployeeVote(string regionID)
{
}
regionId keep coming null to me though the value variable have some value in javascript. any ideas ??
Change
data: 'regionID=' + value,
to
data: {regionID: value},
You need to pass the data as an object literal. Another option (which I dont recommend), which is closer to your idea:
url: '/home/IsEmployeeVoted?regoinID=' + value,
But if you want this to work you would need to remove the type: 'POST' (since GET is the default type).
Few issues:
var value = $('#tblRadio').find('input[type="radio"]:checked').val();
I'd make sure that value is not undefined/null.
use alert(value) before the ajax call.
Also you are specifying GET but POSTING data to the server.
You could also wrap the regionId inside a javascript object, for instance.
$.ajax({
type: "POST",
data: { regionID: value },
url: '/home/IsEmployeeVoted',
success: function (data) {
alert(data); // shows whole dom
if (parseInt(data) > 0) {
$('div.dvVoteWrapper').removeAttr('style');
$('div.popupArea').removeAttr('style');
}
else {
window.location = "/home/EmployeeVote";
}
},
error: function () {
alert("Sorry, The requested property could not be found.");
}
});

How can I RedirectToAction within $.ajax callback?

I use $.ajax() to poll an action method every 5 seconds as follows:
$.ajax({
type: 'GET', url: '/MyController/IsReady/1',
dataType: 'json', success: function (xhr_data) {
if (xhr_data.active == 'pending') {
setTimeout(function () { ajaxRequest(); }, 5000);
}
}
});
and the ActionResult action:
public ActionResult IsReady(int id)
{
if(true)
{
return RedirectToAction("AnotherAction");
}
return Json("pending");
}
I had to change the action return type to ActionResult in order to use RedirectToAction (originally it was JsonResult and I was returning Json(new { active = 'active' };), but it looks to have trouble redirecting and rendering the new View from within the $.ajax() success callback. I need to redirect to "AnotherAction" from within this polling ajax postback. Firebug's response is the View from "AnotherAction", but it's not rendering.
You need to consume the result of your ajax request and use that to run javascript to manually update window.location yourself. For example, something like:
// Your ajax callback:
function(result) {
if (result.redirectUrl != null) {
window.location = result.redirectUrl;
}
}
Where "result" is the argument passed to you by jQuery's ajax method after completion of the ajax request. (And to generate the URL itself, use UrlHelper.GenerateUrl, which is an MVC helper that creates URLs based off of actions/controllers/etc.)
I know this is a super old article but after scouring the web this was still the top answer on Google, and I ended up using a different solution. If you want to use a pure RedirectToAction this works as well. The RedirectToAction response contains the complete markup for the view.
C#:
return RedirectToAction("Action", "Controller", new { myRouteValue = foo});
JS:
$.ajax({
type: "POST",
url: "./PostController/PostAction",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (result) {
if (result.responseText) {
$('body').html(result.responseText);
}
}
});
C# worked well
I just changed the JS because responseText was not working for me:
$.ajax({
type: "POST",
url: posturl,
contentType: false,
processData: false,
async: false,
data: requestjson,
success: function(result) {
if (result) {
$('body').html(result);
}
},
error: function (xhr, status, p3, p4){
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});
You could use the Html.RenderAction helper in a View:
public ActionResult IsReady(int id)
{
if(true)
{
ViewBag.Action = "AnotherAction";
return PartialView("_AjaxRedirect");
}
return Json("pending");
}
And in the "_AjaxRedirect" partial view:
#{
string action = ViewBag.ActionName;
Html.RenderAction(action);
}
Reference:
https://stackoverflow.com/a/49137153/150342

Resources