The original issue was that JQuery Ajax won't call succuess after hitting the C# method. By looking at a similar issue here: jQuery Ajax not returning success i see that the solution was to add: $(parentForm).submit(function(event) { event.preventDefault();
However, after doing this, the Ajax code doesn't seem to execute. I do hit the JS function though, but it stops before it executes Ajax code.
My Html code looks like this
@{
const string formId = "parentForm";
}
@using (Html.BeginForm("EditChannel", "Channel", FormMethod.Post, new { id = formId }))
{
Html.RenderPartial("EditChannelForm", Model);
<br /><br />
<input type="button" value="Save" onclick="editChannel('@Model.ChannelViewModel.ID', @formId)" />
}
I submit this form in the JS code (when the button above is clicked) that looks like this:
function editChannel(channelId, parentForm) {
$(parentForm).submit(function(event) {
event.preventDefault();
$.ajax({
url: "/Channel/EditChannel/",
type: "POST",
cache: false,
data: {
id: channelId,
updatedModel: parentForm
},
success: function(msg) {
alert("Msg: " + msg);
if (msg === "ChangeOfSensitiveData") {
showAlertOnChangeOfSensitiveData('sensitivDataMsgDiv');
} else {
alert("Else");
}
},
error: function(msg) {
alert("error");
}
});
});
}
I do hit the JS function, but the ajax never executes, and therefore not calling the C# method. If I only do like this:
function editChannel(channelId, parentForm) { $(parentForm).submit() ...
Then the ajax code executes and hits the C# method, but never hits the success function.
The C# looks like this:
[HttpPost]
public ActionResult EditChannel(int id, ChannelAndLocationViewModel updatedModel)
{
updatedModel.LocationItemViewModels = GetLocationItems();
if (ModelState.IsValid)
{
ChannelModel channel = null;
using (var context = new MaaneGrisContext())
{
var oldUnit = context.Channels.Where(c => c.ID == id).Select(c => c.Unit).SingleOrDefault();
var newUnit = updatedModel.ChannelViewModel.Unit;
if (oldUnit != null && !oldUnit.Equals(newUnit))
{
return Content("ChangeOfSensitiveData");
}
...
Aucun commentaire:
Enregistrer un commentaire