.ajax get keep data keep coming null in controller - asp.net-mvc

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.");
}
});

Related

Failed to call action method from AJAX

I have a JavaScript method dotrack(). I am calling an action UpdateJson from the JavaScript through AJAX. I am passing JSON data type and the method will return true/false. After executing system is going to success block but the returned value is not true/false.
My question is, whether the system is calling the action properly or not.
function doTrack() {
var D = { 'pageUrl': PageURL, 'linkUrl': linkURL, 'linkName': linkText, 'linkType': ControlType, 'leadId': LeadID, 'userType': UserType, 'portalId': PortalID, 'languageId': LanguageID, 'countryId': CountryID };
D = JSON.stringify(D);
$.ajax({
type: "POST",
url: "portal/UpdateJson",
data: D,
contentType: "application/json; charset=utf-8",
success: function (result) {
if(result == true)
alert("Success");
else
alert(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError + " :: " + ajaxOptions);
//alert('unable to complete ajax request.');
}
});
}
Controller is Portal & Action is UpdateJson:
[HttpPost]
public ActionResult UpdateJson(string pageUrl, string linkUrl, string linkName, string linkType, string leadId, string userType, string portalId, string languageId, string countryId)
{
//do stuff
return Json(true);
}
Please help.
Your ajax code is working fine.
You just need to use the result variable directly instead of result.val.
success: function (result) {
exists = (result);
alert(exists);
}
If you want to use val property, you need to return an object that has val property too.
return Json(new { val = true });
Also you should use Url.Action for preventing incorrect URL.
url: "#Url.Action("UpdateJson", "portal")"

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.

Presenting Modal After Form Submission in MVC

I am trying to create a modal that will tell the user their submission was successfully submitted. This works fairly well, but the only problem is I have to declare each of my properties and assign it a value, then in the Json method I have accept all those parameters then do something with them. Is there any way to do this with a ViewModel? Or any otherway that this can be done using a ViewModel?
controller:
public Json Send(string var1, string var2)
{
...
if(valid)
return new Json(true, JsonRequestBehavior.AllowGet);
else
return new Json(false, JsonRequestBehavior.AllowGet);
}
javascript:
function submitData() {
$.ajax({
url: "/Report/Send",
type: "POST",
dataType: "json",
data: { var1 = Model.var1, var2 = Model.var2... },
success: function (data) {
if(data) {
showDialog();
}
else {
$("#errorDiv").load('Report/Error/');
}
},
error: function (somefunction) { }
});
}
Yes, create a ViewModel POCO class:
var myJsonResult = new { result: true };
return Json(myJsonResult);
You can also use a strongly typed ViewModel and return that:
var myJsonResult = new CustomResult { result: true };
return Json(myJsonResult);
Then just check that property on the class in your success function:
success: function (data) {
if(data.result) {
showDialog();
}
else if(!data.result) {
$("#errorDiv").load('Report/Error/');
}
},
EDIT:
You might also want to look at jquery's .serialize() method:
data: $("#myForm").serialize()
This will be useful if you bind your ViewModel to form elements and need to post them back to the server.

jQuery Ajax call to controller

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")'

Resources