Knockout object passed to Controller as JSon MVC ASP.Net - ajax

I am trying to pass knockout object as below,
When i pass the data using // ko.utils.postJson only without any the AJAx the data is passed to my controller to the "task", but when i try to post by Ajax I get a null value for task
function TaskListViewModel() {
var self = this;
self.availableMeals = [
{ UserName: "Standard", UserId: 0 },
{ UserName: "Premium", UserId: 34 },
{ UserName: "Ultimate", UserId: 290 }
];
self.save = function () {
// ko.utils.postJson(location.href, { task: this.availableMeals });
$.ajax(location.href,{
data: ko.toJSON({ task: this.availableMeals });,
type: 'POST',
dataType:'json',
contentType: 'application/json',
success: function (result) { alert(result) }
});
};
}
ko.applyBindings(new TaskListViewModel());
To the Controller as below,
[HttpPost]
public ActionResult About([FromJson] IEnumerable<UserProfile> task)
{
return RedirectToAction("Login","Account");
}

I would try changing your code to call the stored self reference in your Ajax call as follows:
$.ajax(location.href,{
data: ko.toJSON({ task: self.availableMeals });,
type: 'POST',
dataType:'json',
contentType: 'application/json',
success: function (result) { alert(result) }
});
};
I'm guessing that you are having a scope issues where this is losing it's reference in your Ajax call.

Related

Passing multiple ajax parameters to mvc controller

I can pass a serialized form to a mvc controller no problems with code below and all is populated
$("#btnExecuteJob").on("click", function (e) {
var frmForm1 = $("#form1").serialize();
$.ajax({
cache: false,
url: "/mvcController/executeJob",
dataType: 'json',
type: 'POST',
data: frmForm1,
success: function (resp) {},
error: function (resp) {}
});
});
Controller
[HttpPost]
public ActionResult executeJob(runDetails jobDetails)
{
//
// Process
//
return View();
}
I have added a second form to my view and now want to pass both to the controller so I tried
$("#btnExecuteJob").on("click", function (e) {
var frmForm1 = $("#form1").serialize();
var frmForm2 = $("#form2").serialize();
$.ajax({
cache: false,
url: "/jobScheduler/executeJob",
dataType: 'json',
type: 'POST',
data: {
jobDetails: frmForm1,
jobParameters: frmForm2
},
success: function (resp) {},
error: function (resp) {}
});
});
Controller
public ActionResult executeJob(runDetails jobDetails, runParams jobParameters)
{
//
// Process
//
return View();
}
and neither jobDetails or jobParams is populated, both work individually as first example
and all details are populated, any help much appreciated,
both forms really need to be separate in the controller

Passing parameter to MVC Action via Ajax always null

I looked at related questions to to form my ajax request but I can't figure out why this isn't working as the param is always null in the acion
I've done a console.log to check that item in 'data: { data: item }' has a value
//action
public async Task<IActionResult> DeleteMedia(string data)
{
$("#mediaTable").on('click', 'td:nth-child(7)', function () {
var item = $(this).parent().attr("id");
$("#MediaToDownload").val(item);
$.ajax({
url: '#Url.Action("DeleteMedia", "Home")',
type: 'get',
cache: false,
processData: false,
contentType: false,
data: { data: item },
success: function (data) {
location.href = data;
}
});
});
You need to send just the string, as JSON:
data: JSON.stringify(item)

How do I POST collection of data to controller action

I have following code to send DATA to controller action and return the plain HTML
I am getting empty object in controller action.
var employees = [
{ Title: "John", DataType: 1 },
{ Title: "Anna", DataType: 2 },
{ Title: "Peter", DataType: 3 }
];
$("#btn-continueedit").click(function () {
$.ajax({
type: 'POST', // I tried post also here
cache: false,
url:'/user/UserinfoWizard',
data: { values: employees },
success: function (data) {
$("#editUserInfo").html(data);
}
});
return false;
});
Here is my controller action
[HttpPost]
public ActionResult UserInfoWizard(List<UserInfoEditDetail> values)
{
// I get empty object 'values' here :(
}
The data passed with the ajax call should be an object containing the parameter which you want to use in the controller action. Your action expects a values parameter passed with the data, so your data object should be data: { values: getSelectedAttributes() }
JavaScript:
$("#btn-continueedit").click(function () {
$.ajax({
type: 'POST',
//..
data: { values: getSelectedAttributes() }, //Use the data object with values
//..
});
return false;
});
C#:
[HttpPost]
public ActionResult UserInfoWizard(object values) // parameter name should match the name passed in data object
{
//..
}
EDIT
Indeed you action expects an object, while your values is an array. I don't know what the values are, but in your action you should have the int[] values or string[] values as parameter or any other array type you are expecting.
$("#btn-continueedit").click(function () {
$.ajax({
type: 'GET', // I tried post also here
cache: false,
dataType:JSON,
url:'/user/UserinfoWizard',
data: JSON.stringify({ data:getSelectedAttributes()}),
success: function (data) {
$("#editUserInfo").html(data);
}
});
return false;
});
Updated:
When you are passing data during an ajax call, it should be in the form of an object and not an array

When i call ajax there url wrong why?

I have a one Edit.cshtml page and there is 1 partial template call. in that template I make an ajax call and my controller is home and action name is savedata
ajax function
$.ajax({
url: "CountryZone/SaveData",
type: 'POST',
data: { data: selectedID, id: id },
dataType: "html",
success: function (result) {
alert("Success");
},
error: function (result) {
data.str = null;
alert("Error");
},
});
controller:--
public ActionResult Savedata(string data, int CountryZoneId)
{
return null;
}
now when my ajax call is going
there is url wrong :--- url is Home/edit/Home/Savedata instead of this there is only Home/SaveData
It's a bad idea to hardcode urls in MVC application.
Change this line:
url: "CountryZone/SaveData",
To this:
url: "/CountryZone/SaveData",
I suggest at least using Url.Action in the view and storing it in the js variable.
Use standard MVC code as below:
url: '#Url.Action("SaveData","CountryZone")',
Full Code
$.ajax({
url: '#Url.Action("SaveData","CountryZone")',
type: 'POST',
data: { data: selectedID, CountryZoneId: id },
dataType: "html",
success: function (result) {
alert("Success");
},
error: function (result) {
data.str = null;
alert("Error");
},
});
[HttpPost]
public ActionResult Savedata(string data, int CountryZoneId)
{
return null;
}

Use Ajax and JsonResult in ASP.NET MVC 3

I need to get string array or list with ajax and Action, this is my Implementation:
This is my html Dom of view of Index action in AccessMenuController:
<div class="RoleAccess">
<select name="RoleDropDown">
<option value="0">Select Role</option>
<option value="61AD3FD9-C080-4BB1-8012-2A25309B0AAF">AdminRole</option>
<option value="8A330699-57E1-4FDB-8C8E-99FFDE299AC5">Role2</option>
<option value="004E39C2-4FFC-4353-A06E-30AC887619EF">Role3</option>
</select>
</div>
My Controller:
namespace MyProject.Areas.GlobalAccess.Controllers {
public class AccessMenuController : Controller {
public ActionResult Index() { return View();}
[HttpPost]
public JsonResult RoleDropDownChanged(string roleId) {
Guid RoleId = new Guid(roleId);
//Some implement
List<string> actions = new List<string>();
for(int i = 0; i <= 10; i++)
actions.Add(i.ToString());
return Json(actions.ToArray(), JsonRequestBehavior.AllowGet);
}
}
}
and the script:
$(document).ready(function () {
//Handle Checks of Actions by RoleName Changed
$('div.RoleAccess select').change(function () {
RoleChangeHandler();
});
function RoleChangeHandler() {
$.ajax({
url: '#Url.Action("RoleDropDownChanged")',
type: 'POST',
data: { 'roleId': '61AD3FD9-C080-4BB1-8012-2A25309B0AAF' },
dataType: 'json',
processData: false,
contentType: 'application/json; charset=utf-8',
success: function (data) { SuccessRoleChangeHandler(data); },
error: OnFailRoleChangeHandler
});
return false;
}
function SuccessRoleChangeHandler(data) {
alert("in success role change");
}
function OnFailRoleChangeHandler(result) {
alert('in OnFailRoleChangeHandler');
}
And the problem is with all change of dropdown just Onfail function run and alert me "in OnFailRoleChangeHandler", also I check the RoleDropDownChanged Action with breakpoint and that never run, where is the problem?
UPDATE
when I load the page by chrome there is an error in console window:
http://MyProject/GlobalAccess/AccessMenu/#Url.Action(%22RoleDropDownChanged%22) 404 (Not Found) jquery-1.7.1.js:8102
Remove this setting:
contentType: 'application/json; charset=utf-8',
You are not sending any JSON to the server.
If you want to keep this setting then make sure that you are sending a valid JSON to your server:
data: JSON.stringify({ 'roleId': '61AD3FD9-C080-4BB1-8012-2A25309B0AAF' })
So:
$.ajax({
url: '#Url.Action("RoleDropDownChanged")',
type: 'POST',
data: { 'roleId': '61AD3FD9-C080-4BB1-8012-2A25309B0AAF' },
success: SuccessRoleChangeHandler,
error: OnFailRoleChangeHandler
});
should work (at least it does for me) with the following action:
[HttpPost]
public ActionResult RoleDropDownChanged(Guid roleId)
{
var actions = Enumerable.Range(1, 10).Select(x => x.ToString()).ToList();
return Json(actions);
}
UPDATE:
According to your comments it looks like you are trying to use server side helpers in a separate javascript which is not possible. Here's what I would suggest you. Start by providing the url when generating your dropdown:
<div class="RoleAccess">
#Html.DropDownListFor(
x => x.RoleDropDown,
Model.Roles,
"-- Select role --",
new {
data_url = Url.Action("RoleDropDownChanged")
}
)
</div>
and then in your separate javascript file:
$(document).ready(function() {
$('div.RoleAccess select').change(function () {
var url = $(this).data('url');
$.ajax({
url: url,
type: 'POST',
data: { 'roleId': '61AD3FD9-C080-4BB1-8012-2A25309B0AAF' },
success: function(result) {
alert('success');
},
error: function() {
alert('error');
}
});
});
});
and then of course you could replace the hardcoded roleId with the currently selected value:
data: { 'roleId': $(this).val() }
Move your $(document).ready function to your View like this:
<script type="text/javascript">
$(document).ready(function () {
//Handle Checks of Actions by RoleName Changed
$('div.RoleAccess select').change(function () {
RoleChangeHandler('#Url.Action("RoleDropDownChanged")');
});
});
</script>
Then in your JS file add url parameter to your function and change ajax call:
function RoleChangeHandler(pageUrl) {
$.ajax({
url: pageUrl,
type: 'POST',
data: { 'roleId': '61AD3FD9-C080-4BB1-8012-2A25309B0AAF' },
dataType: 'json',
processData: false,
contentType: 'application/json; charset=utf-8',
success: function (data) { SuccessRoleChangeHandler(data); },
error: OnFailRoleChangeHandler
});
return false;
}
This should work as you expected.
If your script resides in a .JS file then this is not going to work as it'll be treated as plain text. You can either move entire script to the view or you can re-factor script so that majority of the script remains in the .JS and you then pass relevant values from the view.

Resources