Ajax call does not work in mvc 4 - c#

I am pulling my hair. For the love of my life I cannot make this work. I have a form in my view:
<div id="cancel" class="cancel">
<form method="post" class="cancelForm">
<input type="hidden" class="cancelId" name="cancelId" value="#appliedLvl.LeavesId" />
<input id="cancelMe" class="cancelMe" type="submit" value="Cancel"/>
</form>
</div>
The javascript
$(document).ready(function () {
$(".cancelForm").submit(function () {
var MYcancelId = $('.cancelId').val();
$.ajax({
type: "POST",
url: "/Home/Cancel",
success: function (result) {
alert("ok");
},
error: function (request, status, error) {
debugger;
confirm(request);
}
});
})
});
And the Controller
[HttpPost]
public ActionResult Cancel(Guid cancelId )
{
//do stuff here
return PartialView();
}
I always get into the error function of the ajax. No matter what I have tried. This same javascript code works perfectly on my php projects. Don't know what is wrong here. Thanks in advace for any help.
Edit
The error here was the fact that I was expecting in the Action a Guid not a string!

You aren't passing in a cancelId parameter, so it isn't seeing your controller method.
$(document).ready(function () {
$(".cancelForm").submit(function () {
var MYcancelId = $('.cancelId').val();
$.ajax({
type: "POST",
url: "/Home/Cancel",
data: { cancelId = MYcancelId },
success: function (result) {
alert("ok");
},
error: function (request, status, error) {
debugger;
confirm(request);
}
});
})
});

Related

ASP.NET MVC AJAX Call to Controller Not Returning any Data

I'm trying to call an ASP.NET MVC controller using an AJAX Call. Basically I want to return customer details based on the ID selected from a dropdownlist. On debugging, controller is being hit and returning data in JSON format however, on debugging javascript, it never gets to success, failure or error.
Here is the code I'm using:
View:
<script type="text/javascript">
$(document).ready(function () {
$("#CustomerId").select2({
placeholder: "Select a customer"
});
$("#CustomerId").change(function () {
var param = $("#CustomerId Option:Selected").val();
$.ajax({
type: 'GET',
data: { Id: param },
url: '/QuickInvoices/GetCustDetails',
success: {
function(response) {
if (response != null) {
alert("hello");
$('customer_CompanyName').val(response.CompanyName);
}
else {
alert("something went wrong!");
}
}
},
failure: function (response) {
alert('failed');
},
error: function (response) {
alert('error' + response.responseText);
}
});
});
});
</script>
Controller:
[HttpGet]
public JsonResult GetCustDetails(int Id)
{
Customer customer = db.Customers.Where(x => x.Id == Id)
.SingleOrDefault<Customer>();
return Json(customer, JsonRequestBehavior.AllowGet);
}
Can someone help please?
Please try below Code sample and check the Request & Response of network tab
you will get batter Idea
$(document).ready(function () {
$("#CustomerId").select2({
placeholder: "Select a customer"
});
$("#CustomerId").change(function () {
var param = $("#CustomerId Option:Selected").val();
$.ajax({
type: "POST",
url: '#Url.Action("GetCustDetails", "QuickInvoices")',
data: { Id: param },
dataType: "json"
contentType: 'application/json; charset=utf-8',
success: function(data) {
alert(data.msg);
},
error: function() {
alert("Error occured!!")
}
});
});
});

Redirect with Ajax POST

i'm new with ajax and i'm trying to call a post action from an ajax method like that
$(".buttonSelection").click(function () {
selectedId = $(this).parents('tr:first').children('td:first').children('input:first').attr('value');
$.ajax({
// Call MaSelection action method
url: "/DemandeLocation/MaSelectionOffre",
data: { id: selectedId },
type: 'Post',
success: function (msg) {
window.location.replace('#Url.Content("~/DemandeLocation/MaSelectionOffre")');
},
error: function (xhr) {
alert("something seems wrong");
}
});
});
my post method goes with success but instead of redirectin me to the MaSelection View it return the first view where i call the method, so i tried to put a "Success" fragment in my ajax method and i puted a location replace by "Ma selection" view but i know that the view lose the id so it become null, how can i do it with Ajax,
here my post action for more details
[HttpPost]
[Authorize(Roles = "Locataire")]
public ActionResult MaSelectionOffre(string id)
{
int DemandeLocationGetbyId = Convert.ToInt32(id);
var selectionOffre = db.SelectionOffreLocationSet.Where(model => model.DemandeLocationPublication_ID == DemandeLocationGetbyId).ToList();
return View("MaSelectionOffre", selectionOffre);
}
use json as datatype;
$(".buttonSelection").click(function () {
selectedId = $(this).parents('tr:first').children('td:first').children('input:first').attr('value');
$.ajax({
// Call MaSelection action method
url: "/DemandeLocation/MaSelectionOffre",
dataType:"json",
data: { id: selectedId },
type: 'Post',
success: function (msg) {
window.location.href = msg.redirect;
},
error: function (xhr) {
alert("something seems wrong");
}
});
});
also you need this ;
Convert object to JSON string in C#
If you want redirect page, after ajax call you should use
...
success: function (msg) {
window.location.href = '#Url.Action("MaSelectionOffre", "DemandeLocation")';
},
...
EDIT
If you want replace result, use something like following:
HTML
<div id="updateTargetId">
//table
//tr
//td
//your button that has cssClass buttonSelection
</div>
JS
$(".buttonSelection").click(function () {
selectedId = $(this).parents('tr:first').children('td:first').children('input:first').attr('value');
$.ajax({
// Call MaSelection action method
url: "/DemandeLocation/MaSelectionOffre",
dataType:"json",
data: { id: selectedId },
type: 'Post',
success: function (msg) {
$("#updateTargetId").html(msg);
},
error: function (xhr) {
alert("something seems wrong");
}
});
});
CONTROLLER (return PartialView)
[HttpPost]
[Authorize(Roles = "Locataire")]
public ActionResult MaSelectionOffre(string id)
{
int DemandeLocationGetbyId = Convert.ToInt32(id);
var selectionOffre = db.SelectionOffreLocationSet.Where(model => model.DemandeLocationPublication_ID == DemandeLocationGetbyId).ToList();
return PartialView("MaSelectionOffre", selectionOffre);
}
i changed my action to a get action and in my button i just added window.location.replace with link and ID
<button type="button" class="buttonSelection" onclick="window.location.replace('#Url.Content("~/DemandeLocation/MaSelectionOffre?id="+item.Publication_ID)')"> <span class="ui-icon ui-icon-cart"></span> </button>

Change page in browser after end of controller

How can i change page in browser, after end of controller?
I tryed this:
Html/JS code:
<form>
<button type="submit" onclick="abc()">123</button>
</form>
<script>
function abc()
{
$.post("/", "abc", function () {
});
}
</script>
ASP.NET MVC Code:
[HttpPost]
public ActionResult Index(dynamic response)
{
return Redirect(Request.UrlReferrer.ToString() + "/Home/OtherPage");
}
What am I doing wrong?
[HttpPost]
public ActionResult Index(dynamic response)
{
return RedirectToAction("OtherPage", "Home");
}
Check this solution -
Your Action should be like this -
public ActionResult RedirectMe()
{
return new JsonResult() { Data = "http://www.google.com", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
Then your JQuery POST should be -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function submitForm() {
jQuery.ajax({
type: "POST",
url: "#Url.Action("RedirectMe")",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
window.location.href = data;
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" value="Click" onclick="submitForm()" />
When you Click the button, you will be redirected to the Google. You have to make sure you construct a proper URL (instead of google) and send it back.
If you want to pass some parameters to Action, then follow this way -
public ActionResult RedirectMe(string id)
{
return new JsonResult(){ Data = "http://www.google.com", JsonRequestBehavior = JsonRequestBehavior.AllowGet};
}
Finally your JQuery POST should be -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function submitForm() {
jQuery.ajax({
type: "POST",
url: "#Url.Action("RedirectMe")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ id: "This is my parameter"}),
success: function (data) {
window.location.href = data;
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" value="Click" onclick="submitForm()" />
If you want to redirect to another page in your client code, You may send the new url in a JSON response and use window.location.href property to naviagate to that.
[HttpPost]
public ActionResult Index(dynamic response)
{
//Do your other work
string newUrl=Request.UrlReferrer.ToString() + "/Home/OtherPage";
//It may be better to use the Helper methods to get the url.
return Json(new { NewUrl=newUrl);
}
In your ajax call
$.post("YourURLHEre",{ response :YourDataHere},function(res){
window.location.href=res;
});

Ajax jQuery not always executes action on Controller

I have the Controller method below made in ASP.NET MVC 3 (C#) who returns a PartialView:
public ActionResult InsertEmail(long idPerson)
{
PersonEmailViewModel mail = new PersonEmailViewModel();
mail.email.Person_idPerson = idPerson;
return PartialView(mail);
}
The method that I need to execute on submit form is:
[HttpPost]
public ActionResult InsertNewEmail(PersonEmail mail)
{
mail.idPersonEmail = mail.Insert(mail);
return Json(mail);
}
My partialView contains this code:
#model PlatformLib_MySql.BLL.Person.PersonEmailViewModel
<form action="" id="frmNewEmail" method="post">
<div>
E-mail: #(Html.TextBoxFor(m => m.email.email))
#(Html.HiddenFor(m => m.email.Person_idPerson))
<input type="submit" value="Insert" id="btnSubmitMailInsert" />
<input type="button" value="Cancel" id="btnCancelMailInsert" />
</div>
</form>
In my JS file I run this code on #btnSubmitMailInsert button:
jQuery("#btnSubmitMailInsert").click(function () {
submitNewEmail();
window.location.reload();
});
function submitNewEmail() {
event.preventDefault();
var mail = {
email: jQuery("#frmNewEmail #email_email").val(),
Person_idPerson: jQuery("#frmNewEmail #email_Person_idPerson").val()
};
var request = jQuery.ajax({
url: '/Person/InsertNewEmail',
data: mail,
type: 'POST',
dataType: 'json',
cache: false
});
request.done(function (msg) {
console.log(msg);
});
request.fail(function (msg) {
console.log(msg);
});
}
My problem is focused on Ajax request. Rarely I can make the "happy way", where on submit click, the event is activated on jQuery, calls the method "submitNewEmail()", that calls an Ajax, executes the method on controller and pass with success. But not so... It always returns with fail, not because error returned by controller method, but simply because ajax doesn't runs properly, doesn't execute the method on controller, even with a breakpoint inserted there (on VS2010).
In this JS code posted by me here is an attempt to alternatively solve this problem, unsuccessful.
The original code is:
jQuery.ajax({
url: '/Person/InsertNewEmail',
data: mail,
type: 'POST',
dataType: 'json',
cache: false,
success: function (result) {
debugger;
jQuery("#tblEmail").append("<tr><td>Email inserido</td></tr>");
},
error: function () {
debugger;
alert("Erro ao inserir e-mail.");
}
});
I left the "console.log(msg)" temporary, just to solve this problem.
Can someone of you tell me what is happening, or to point where is my error?
I found the problem. Everything was right, but some detail damaged the code: window.location.reload();
I made some changes in my code, that looks like it:
jQuery.ajax({
url: '/Person/InsertNewEmail',
data: mail,
type: 'POST',
dataType: 'json',
cache: false
}).done(function (data) {
// Do something
});
The another way is right too, the only relevant change was:
jQuery("#btnSubmitMailInsert").click(function () {
event.preventDefault();
submitNewEmail();
// window.location.reload // -> Commented for testing and everything worked fine.
});
Thanks for trying to help me. This helped me so much.

ASP.NET MVC3 and jquery form plugin

I'm using ASP.NET MCV3, jquery 1.5.2 and jquery form plugin.
Here's the sample code:
<script type="text/javascript">
// wait for the DOM to be loaded
$(document).ready(function () {
$('#uploadForm').ajaxForm({
dataType: 'json',
beforeSubmit: function () { alert('beforeSubmit'); },
success: function() { alert('success'); },
error: function () { alert('error'); }
});
});
</script>
<form id="uploadForm" action="#Url.Action("UploadFile")" method="post">
<input type="submit" value="Submit file" />
</form>
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult UploadFile()
{
return Json(new { message = "success" });
}
When I submit the form, I always get the following error message: Expected ';'
I searched SO, Google.. but couldn't find any solution to this problem.
I found Darin's comment here, but I need to have beforeSubmit and success events.
Any help would be greatly appreciated!
I changed dataType from json to text and then I parsed the result. Everything seams to work ok.
<script type="text/javascript">
// wait for the DOM to be loaded
$(document).ready(function () {
$('#uploadForm').ajaxForm({
dataType: 'text',
beforeSubmit: function () { alert('beforeSubmit'); },
success: processJson,
error: function () { alert('error'); }
});
});
function processJson(responseJson) {
var obj = jQuery.parseJSON(responseJson);
alert(obj.message);
}
</script>

Categories

Resources