JQUERY ajax passing null value from MVC View to Controller - asp.net-mvc

hi guys i'm posting some data to controller using jquery ajax, but i am getting null values in my controller,
jQuery code is:
$('#registerCompOff').click(function() {
var compOff = [];
$('div').each(function() {
var curRow = {};
curRow.Description = $(this).find('.reason').val();
curRow.CompOffDate = $(this).find('.datefieldWithWeekends').val();
if (curRow.Description != null && curRow.CompOffDate != null) {
compOff.push(curRow);
}
});
$.ajax({
type: 'POST',
url: this.href,
dataType: 'json',
data: compOff
});
return $('form').valid();
});​
compOff is not null I have checked that...
controller is:
[HttpPost]
public ActionResult RegisterCompOff(RegisterCompOff[] registerCompOff)
{
//return View();
}
can you tell me where i'm going wrong?

Given your original code, change in $.ajax -> data: JSON.stringify(compOff) then add contentType: "application/json; charset=utf-8" and finally change parameter name of controller's action to public ActionResult RegisterCompOff(RegisterCompOff[] compOff). Model binding should kick off then. It did for me.

Edited:
try this :
$.ajax({
type: 'POST',
url: this.href,
dataType: 'json',
traditional: true,
data:
{
CompOffList: compOff
}
});
and change your controller like this :
[HttpPost]
public ActionResult RegisterCompOff(List<RegisterCompOff> CompOffList)
{
//return View();
}
hope this helps

Your r passing javascript object as data wherease jquery ajax method expects a key/value pair list.
Try this
data:{Description:compOff.Description, CompOffDate:compOff.CompOffDate}

Related

Controller in my MVC project returning null from Ajax Post call

I'm not sure to why the controller is receiving a data from an Ajax call . Could i be doing anything wrong?
[HttpPost]
[Route("Product/UpdateDetails")]
public ActionResult UpdateProduct (ProductModel model) <<// model here is null
{
Product p = new Product
{
ProductId = p.ProductId,
Price = p.Price,
};
return View("_ProductDetail"); }
Ajax call below:
var model = {
ProductId: 1,
Price: 270.99,
};
var json = JSON.stringify(model)
$.ajax({
url: '/Product/UpdateDetails',
type: 'Post',
contentType: "application/json; charset=utf-8",
model: model,
success: function (results) {
}
});
//Model
public class Product
{
public int Id {get;set;}
public double Price {get;set;}
}
Can you guys spot anything that i may be doing wrong in the code above ? I can't see anything that i'm doing wrong.
Try this:
$.ajax({
url: '/Product/UpdateDetails',
type: 'Post',
contentType: "application/json; charset=utf-8",
data: json,
success: function (results) {
}
});
You used JSON.Stringify() on your model, but forgot to use the variable "json" on the ajax call, so the ajax was trying to post a "non-json" model.
Also, there is no model setting in ajax calls, the correct one to post your data is data, as you can see here.

jquery ajax load partial view to div tag MVC

I've been searching around with no luck on how to make a jquery call to load a partial view in a div tag on my Index view. Some how I am not getting the partial view to update when I click on a link on my tree. The partial view loads when I first run it b/c I call <div id="divid">
#Html.Partial("_InnerView")</div>. After that nothing happens when I click on the link. Or maybe I am not getting the full picture here. Some mentioned to use $('#divid').load = data; or $('#divid').innerHTML= data; but nothing works for me. This is what I have.
Controller:
public ActionResult Test(string parentEls)
{
if (Request.IsAjaxRequest())
{
Employee employee = new Employee();
employee.Name = parentEls + "1";
return PartialView("_InnerView", employee);
}
return View("_InnerView");
}
Index view:
<div id="divid">
#Html.Partial("_InnerView")</div>
$('#tree a').click(function () {
var parentEls = $(this).parents('ul').map(function () {
return $(this).find('a').first().text();
}).get().join(", ");
$.ajax({
type: 'POST',
url: '#Url.Content("~/Home/Test")',
data: {
parentEls: parentEls
},
success: function(data) {
$('#divid').innerHTML = data;
}
});
});
_InnerView.cshtml:
#model TreeDemo.Models.Employee
EmpName:#Model.Name
UPDATE: I got this to work with this
$.ajax({ url: '/Home/Test/', contentType: 'application/html; charset=utf-8', type: 'GET', dataType: 'html', data: { parentEls: parentEls } })
You have to use
$('#divid').html(data);
instead of
$('#divid').innerHTML = data;
Load Partial View in a div MVC 4
Recently I want load Partal View in Div , after doing lots of R&D and It's work for me
$.ajax({
type: 'POST',
url: '#Url.Content("~/ControllerName/ActionName")',
data: {
title: title
},
success: function(result) {
$('#divid').innerHTML = result;
}
});
And In Partal View Action Controller Code
public PartialViewResult ShowCategoryForm(string title)
{
Model model = new Model();
model.Title = title;
return PartialView("~/Views/ControllerName/PartalView.cshtml", model);
}
I think it can be useful if you check the request/response objects of your call, so you can see what is really happening after you make the call... As per your code, I can notice that you're posting using
$.ajax({
type: 'POST',
url: '#Url.Content("~/Home/Test")',
data: {
parentEls: parentEls
},
success: function(data) {
$('#divid').innerHTML = data;
}
});
but your action is marked for 'getting'... you'd need to have something like this
[HttpPost]
public ActionResult Test(string parentEls)
so MVC can understand that the action should be called when HttpPost verb is used

Controller Action cannot be called from $.Ajax javascript

In MVC, I have written an action in the controller for getting values. The action is as follows..
public void poolshapepdf(List<String> values)
{
...
}
To pass the parameter values to the controller action i pass the values from javascript..
the code is the below,
$.ajax({
type: 'POST',
url: rootDir + "IngroundCalculation/poolshapepdf",
data: { values: collectionPSElmt },
traditional: true,
});
Here collectionPSElmt is an array.
collectionPSElmt[index] = poolshapeValue[index] + "-" + psFeet[index] + "-" + psInch[index];
Here the issue is the controller action cannot be called from the javascript $.Ajax(..).
How do I fix this issue?
You calling the controller by POST and JSON data:
[HttpPost]
public JsonResult poolshapepdf(DataClass[] items)
{
}
Now, make a proper call to your url.
specify the data type as json and always go for success function.
using that you can easily crack the report.
$.ajax({
url: '#Url.Action("poolshapepdf", "IngroundCalculation")',
type: "POST",
dataType: 'json',
data: collectionPSElmt ,
contentType: "application/json; charset=utf-8",
success: function (result) {
alert("Working..");
}
});
And at Controller Side,
[HttpPost]
public JsonResult poolshapepdf(DataClass[] items)
{
// Your Code here....
}

Kendo UI - Ajax MVC - JSON always null

I have a Kendo grid that has been sort-enabled. I want to do an ajax postback using jQuery to send the sort information to the action method to do some action.
var datasource = $(".data-table").data("kendoGrid").dataSource;
$.ajax({
type: 'POST',
url: '#Url.Action("ExportToPDf", "MyController")',
dataType: 'json',
data: { sort: datasource._sort }
});
I'm able to see with a debugger that the correct value is got and passed in the data attribute of the ajax. I used FireBug to confirm that the values are passed during the POST action.
public ActionResult ExportToPDf(List<SortDescription> sort)
{
//Will be doing some action
return null;
}
public class SortDescription
{
public string dir { get; set; }
public string field { get; set; }
}
Sample data from Firebug during POST action
sort[0][dir] asc
sort[0][field] EmployeeRef
When I keep breakpoint in action method, im able to get one item in the list, but the properties appear to be null.
Can anyone please guide me what I do wrong?
Try something like this:
$.ajax({
url: '#Url.Action("ExportToPDf", "MyController")',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({sort: datasource._sort })
})

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