Passing multiple ajax parameters to mvc controller - model-view-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

Related

Unable to 'call' controller action from ajax post

I'm using net.core for the first time today and I'm trying to call an action method from an ajax call:
My Ajax call (from a normal HTML page)
$("#contactMap").click(function (e) {
e.preventDefault();
var url = "/MapObjects/mapContact";
//I've tried MapObjectsController & '#Url.Action("mapContact", 'MapObjects")'; But to no avail
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (result) {
alert("success");
}
});
});
And in my controller:
namespace myName.Controllers
{
public class MapObjectsController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult mapContact()
{
Account account = new Account();
return Json(account);
}
}
}
The 'account' is just a normal model (obvs empty in this case). All I receive is a 404 error in the console though.
As mentioned this is the 1st time I've .net Core (this is code I've written loads of times in 'normal' MVC projects) so it's possible that I'm missing something really obvious.
Thanks,
C
The first, try to call the #Url.Action() explicitly in the Ajax call :
$("#contactMap").click(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("mapContact", "MapObjects")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (result) {
alert("success");
}
});
});
The second, check your routing rules.

ASP.NET & Ajax - How to pass value from ajax to action?

I have a few checkboxes on my page. I have some jquery in place to ensure that only one checkbox is checked at a time. I have assigned a specific value to each checkbox. The below ajax finds the checkbox that is checked and I'm grabbing the value associated to it. How do I pass that value to my action?
AJAX
$("input:checkbox").click(function () {
var PaymentID = document.querySelector('#chkBox:checked').value;
alert(PaymentID); // for test
$.ajax({
type: "POST",
dataType: "json",
data: PaymentID,
contentType: "application/json; charset=utf-8",
url: "#Url.Action("MyAction", "Home")",
success: function () {
return PaymentID; // Failed attempt at passing data.
}
})
})
Action:
[HttpPost]
public ActionResult MyAction(string PaymentID)
{
// Magic
}
Please keep in mind i am fairly new to ajax. Thx guys.
You can pass a javascript object with name PaymentID ( same name as your action method parameter)
data: { PaymentID: PaymentID },
You do not need to specify contentType as you are sending a simply object. Also you do not necessarily need to specify dataType for your ajax call to send the data.
This should work.
var PaymentID = "some value";
$.ajax({
type: "POST",
data: { PaymentID: PaymentID },
url: "#Url.Action("MyAction", "Home")",
success: function (response) {
console.log('response', response);
}
});
Or you can use the $.post method.
$.post("#Url.Action("MyAction", "Home")",{ PaymentID: PaymentID }, function(response) {
console.log('response', response);
});

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;
}

Rendering a simple ASP.NET MVC PartialView using JQuery Ajax Post call

I have the following code in my MVC controller:
[HttpPost]
public PartialViewResult GetPartialDiv(int id /* drop down value */)
{
PartyInvites.Models.GuestResponse guestResponse = new PartyInvites.Models.GuestResponse();
guestResponse.Name = "this was generated from this ddl id:";
return PartialView("MyPartialView", guestResponse);
}
Then this in my javascript at the top of my view:
$(document).ready(function () {
$(".SelectedCustomer").change( function (event) {
$.ajax({
url: "#Url.Action("GetPartialDiv/")" + $(this).val(),
data: { id : $(this).val() /* add other additional parameters */ },
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
SetData(data);
}
});
});
function SetData(data)
{
$("#divPartialView").html( data ); // HTML DOM replace
}
});
Then finally my html:
<div id="divPartialView">
#Html.Partial("~/Views/MyPartialView.cshtml", Model)
</div>
Essentially when a my dropdown tag (which has a class called SelectedCustomer) has an onchange fired it should fire the post call. Which it does and I can debug into my controller and it even goes back successfully passes back the PartialViewResult but then the success SetData() function doesnt get called and instead I get a 500 internal server error as below on Google CHromes console:
POST http:// localhost:45108/Home/GetPartialDiv/1 500 (Internal Server
Error) jquery-1.9.1.min.js:5 b.ajaxTransport.send
jquery-1.9.1.min.js:5 b.extend.ajax jquery-1.9.1.min.js:5 (anonymous
function) 5:25 b.event.dispatch jquery-1.9.1.min.js:3
b.event.add.v.handle jquery-1.9.1.min.js:3
Any ideas what I'm doing wrong? I've googled this one to death!
this line is not true: url: "#Url.Action("GetPartialDiv/")" + $(this).val(),
$.ajax data attribute is already included route value. So just define url in url attribute. write route value in data attribute.
$(".SelectedCustomer").change( function (event) {
$.ajax({
url: '#Url.Action("GetPartialDiv", "Home")',
data: { id : $(this).val() /* add other additional parameters */ },
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
SetData(data);
}
});
});

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