RLH RLH - 5 months ago 11
jQuery Question

JQuery not calling HttpPost method on my controller. How can I fix this, or what could be going wrong?

I have a special case where I need to have a grid with an "Add New Record" row, that exists within an MVC form.

Since I can't submit the new record details, without submitting the entire form, I decided to make the record submit button call a Javascript method that should POST the data to a method on my controller. In short, here is an example of what I'm doing. The code below is copy-and-pasted from my project, with only minor modifications for brevity.

...
<table>
CODE HERE FOR MY GRID...
</table>
...
<input class="data_field" id="MainSession_Name" type="text" />
<input class="data_field" id="MainSession_Type" type="text" />
<button id="btnAddMainSession" class="button" onclick="SubmitMainSession()" type="button">Add Session</button>
...
<script>
var SubmitMainSession = function()
{
var data = {
Name: $('MainSession_Name').val(),
RecType: $('MainSession_Type').val(),
};

$.post(
{


url: "/Session/Add",
data: data,
callback: function(res, status)
{
if (res !== "OK")
alert("There was a problem processing the request. " + res);
else
location.reload(true);
}
});
}
</script>


My intent is simple. After the user enters new details for a session, they will click on the
Add Session
button. JQuery will make a POST request passing my data to my page controller.

Here is an abbreviated variation of my controller:

//Index that initially loads the data.
public ActionResult Index(int id = -1)
{
SessionModel sm = new SessionModel(id);
sm.CanEdit = true;
return View(sm);
}

//The containing model manages a HUGE form,
//across multiple BootStrap.js tabs. We save
//all other, non-sub-record related deets here.
public ActionResult Submit(SessionModel model)
{
model.Save();
return Redirect(Url.Content("~/"));
}

//Since there are multiple grids, I need to
//have a way to add new Session records.
//This is my first attempt at trying to
//create a POST method on my controller.
[HttpPost]
public string Add(AddSessionObject data)
{
//If I can ever get here, I'll save the data.
return "OK";
}

public class AddSessionObject
{
public string Name;
public string RecType;
}


What I'm experiencing is that when I make the $.post(...) call in JQuery, MVC always calls the Index(...) method, rather than the Add(...) method. What am I doing wrong?

Answer

try using this syntax:

var data = {
  Name: $('MainSession_Name').val(),
  RecType: $('MainSession_Type').val(),
};

$.post("/Session/Add", data, function(res, status) {
  if (res !== "OK")
    alert("There was a problem processing the request. " + res);
  else
    location.reload(true);
});

https://api.jquery.com/jquery.post/

Comments