Pass action with model to jquery ajax success call - asp.net-mvc-3

My Jquery Ajax Call. How to return model from action to ajax and pass to another action.
function ChangeName(id)
{
var name=$("#name").val();
$.ajax({
cache:false,
url: "#Url.Action("EditName", "Order")",
data: "Name=" +name+"&Id="+id ,
type: "POST",
success: function (data) {
window.location.href=data.Url;//doesnt work passes null model
}
});
}
public ActionResult EditName(string name,int id)
{
var product= GetProduct(id);
product.Name=name;
UpdateProduct(product);
var model=new ProdModel(){id=id};
return Json(new
{
Url = Url.Action("Test","Order",new{model=model})
},JsonRequestBehavior.AllowGet);
}
public ActionResult Test(ProdModel model)//Model null
{
return RedirectToAction("List", "Product");
}
I have tried this but not getting success.

Try this
function ChangeName(id)
{
var name=$("#name").val();
var params = {
Name: name,
Id: id
};
$.ajax({
cache:false,
url: '#Url.Action("EditName", "Order")',
data: JSON.stringify(params),
type: "POST",
success: function (data) {
window.location.href=data.Url;//doesnt work passes null model
}
});
}
[HttpPost]
public ActionResult EditName(string name,int id)
{
var product= GetProduct(id);
product.Name=name;
UpdateProduct(product);
var model=new ProdModel(){id=id};
return Json(new
{
Url = Url.Action("Test","Order",new{model=product})
},JsonRequestBehavior.AllowGet);
}

Try as follows
In Edit Action try returning the model instead of url,
public josnResult EditName(string name,int id)
{
var product= GetProduct(id);
product.Name=name;
UpdateProduct(product);
var model=new ProdModel(){id=id};
return Json(model,JsonRequestBehavior.AllowGet);
}
Then in ajax Success call you can make another call to Test Action
$.ajax({
cache:false,
url: '#Url.Action("EditName", "Order")',
data: JSON.stringify(params),
type: "POST",
success: function (data) {
CallTestAction(data);
}
});
var CallTestAction = function(data) {
$.ajax({
cache:false,
url: '#Url.Action("Test", "Order")',
data: {model = data},
type: "POST",
success: function (data) {
}
});
};

Related

Ajax post zero to controller

I'm trying to POST an int with Ajax to my controller
Js
<script>
function FillCity() {
var provinceId = $(provinces).val();
$.ajax({
url: "FillCity",
type: "POST",
data: { id: provinceId },
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#cities").html(""); // clear before appending new list
$.each(data, function (i, city) {
$("#cities").append(
$('<option></option>').val(city.Id).html(city.Name));
});
}
});
}
</script>
code in my controller :
[HttpPost]
public ActionResult FillCity(int id)
{
var cities = _context.City.Where(c => c.ProvinceId == 5);
return Json(cities);
}
but it always post 0 as id, I tried digits instead of provinceId, but it rtills send 0
You should create an class that have a Id Property.
public class ProvinceIdDto
{
public int Id { get; set; }
}
replace int id with ProvinceIdDto model in action
[HttpPost]
public ActionResult FillCity(ProvinceIdDto model)
{
var cities = _context.City.Where(c => c.ProvinceId == model.Id);
return Json(cities);
}
replace { id: provinceId } with JSON.stringify({ Id: provinceId }),
<script>
function FillCity() {
var provinceId = $(provinces).val();
$.ajax({
url: "FillCity",
type: "POST",
data: JSON.stringify({ Id: provinceId }),
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#cities").html(""); // clear before appending new list
$.each(data, function (i, city) {
$("#cities").append(
$('<option></option>').val(city.Id).html(city.Name));
});
}
});
}
</script>
Another options is you can replace HttpPost method with HttpGet and pass id to action like this.
Change type: "POST", to type: "GET",
<script>
function FillCity() {
var provinceId = $(provinces).val();
$.ajax({
url: "FillCity?id="+provinceId,//<-- NOTE THIS
type: "GET",//<-- NOTE THIS
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#cities").html(""); // clear before appending new list
$.each(data, function (i, city) {
$("#cities").append(
$('<option></option>').val(city.Id).html(city.Name));
});
}
});
}
</script>
C#
[HttpGet]
public ActionResult FillCity(int id)
{
var cities = _context.City.Where(c => c.ProvinceId == id);
return Json(cities);
}
when you do { id: provinceId } you are creating an object with property id
in your controller you are just expecting an id. You will need to ether:
A pass it as a query parameter url: "FillCity?id=" + provinceId
B create an object to be parsed from the request body.
public class Payload {
public int Id {get;set;}
}
and use it like this
public ActionResult FillCity([FromBody] Payload payload)
Can you verify this statement has a value:
var provinceId = $(provinces).val();
It's possible that isn't finding what you are looking for, and because you have the type int as a parameter, it defaults it to "0".
You shouldn't need to change it to a GET and your MVC method is fine as is. You can see from JQuery's own sample it should work:
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
I think it might not be finding the input field successfully.

HttpPostedFileBase null on controller / ajax resquest

I'm trying to upload a file and send it to controller, but it's always returning null. Here's the code:
[HttpPost, ValidateAntiForgeryToken]
public JsonResult Edita(string nome, string login, string email, string dataNascimento, HttpPostedFileBase avatar)
{
if (ModelState.IsValid)
{
......
}
}
Here's the javascript code.... am i missing anything? I've tried with formData as well, but couldn't make it work
$(document).ready(function () {
$("#btnSalvar").click(() => {
if (form.valid()) {
var url = "#Url.Action("Edita", "Usuario")";
let myFormData = $("#formUsuario").serializeArray();
$.ajax(
{
type: "POST",
url: url,
data: myFormData,
dataType: 'json',
autoUpload: true,
success: function (data) {
if (data.status == "OK") {
$("#userModal").modal("hide");
}
}
});
}
});
});
I found out the solution for this issue. My had the #Html.AntiForgeryToken() validation, so i removed it and it worked!

Ajax form submit calling method twice in ASP.NET MVC

I have a weird scenario happens when I send my ajax request that has 2 objects
first time it passes the second obj with the right value while the first object is null.Then second call it passes the first obj with value and the second obj as null
Here's my ajax method
var serializedForm = $(form).serialize();
var postData = {
merchTask: obj,
items: arrItems
};
$.ajax({
type: "POST",
url: $(form).attr('action'),
contentType: "application/json; charset=utf-8",
dataType:'json',
data: JSON.stringify(postData),
success: function (response) {
alert('done');
},
error: function (xhr, status, error) {
alert("Oops..." + xhr.responseText);
}
});
And here's my action in controller
public ActionResult EditTask(Task merchTask, string[] items)
{
short CompanyID = Convert.ToInt16((gSessions.GetSessionValue(gSessionsData.Company) as Company).ID);
try
{
merchTask.CompanyID = CompanyID;
if (merchTask.TaskID != 0)
{
taskTemplatesBF.Update(merchTask);
}
else
{
taskTemplatesBF.InsertMerchTask(merchTask);
}
string[] selectedLst = items;
foreach (string item in selectedLst)
{
taskTemplatesBF.InsertItemsLink(CompanyID,merchTask.TaskID,merchTask.ItemCode);
}
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
ModelState.AddModelError("", ex.InnerException.Message);
}
ModelState.AddModelError("", ex.Message);
}
return RedirectToAction("TasksTemplates", "Merch");
}
*I found a workaround to send each object separately in different ajax
but what's wrong when I send them in one request?
You have added a lot of code in the question but missed the code that was actually needed.
Okay add the event.preventDefault(); and event.stopImmediatePropagation(); functions inside your form summit event as follows:
$(document).ready(function(){
$("formId").on('submit',function(event){
event.preventDefault();
event.stopImmediatePropagation();
var serializedForm = $(form).serialize();
var postData = {
merchTask: obj,
items: arrItems
};
$.ajax({
type: "POST",
url: $(form).attr('action'),
contentType: "application/json; charset=utf-8",
dataType:'json',
data: JSON.stringify(postData),
success: function (response) {
alert('done');
},
error: function (xhr, status, error) {
alert("Oops..." + xhr.responseText);
}
});
});
});
Hope this will solve your problem.

asp.net mvc ajax crazy

From a page Index.cshtml, i have a very simple ajax call
controller1 and controller2 have the same action:
public ActionResult abc(string name)
{
return new JsonResult()
{
Data = new
{
success = true,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
}
};
}
$(document).ready(function ($) {
$.ajax({
url: '#Url.Action("abc", "controller1")',
type: 'POST',
data: { name: 'John' },
dataType: 'json',
success: function (result) {
if (result.success) {
alert("ok");
}
else {
alert(result.error);
}
}
});
});
not work
however using exactly the same syntax, just change the controller, it works !!!.
abc action is the same.
$.ajax({
url: '#Url.Action("abc","controller2")',
type: 'POST',
data: { name: 'John' },
dataType: 'json',
success: function (result) {
if (result.success) {
alert("ok");
}
else {
alert(result.error);
}
}
});
it drives me crazy, don't know what happen. On a new project, i tried the same code, it works perfectly, but not on my current work.

asp.net mvc 3 json does not work

This is my jquery with json
$('#btnVerificationOk').click(function () {
var verId = $('#trans_verification_id').val();
var verCode = $('#trans_verification_code').val();
$.ajax({
url: '/Profile/CompleteTransactions',
type: 'POST',
data: { },
dataType: 'json',
success: function (result) {
alert(result);
},
error: function () {
alert('ERROR ERROR !!!!!!!!!!!!');
}
});
});
And My C# method:
[Authorize]
[HttpPost]
private JsonResult CompleteTransactions()
{
return Json("Done");
}
Its always alerts 'ERROR ERROR !!!!!!!!!!!!' i tried debugging but CompleteTransactions method is not firing
And this is my second json which is bellow and works good
$('#btnTransfareOk').click(function () {
var userName = $('#transfare_username').val();
var amount = $('#transfare_amount').val();
if (userName == '' || amount == '') {
$('#transfare_error_list').html('Please fill boxes.');
} else {
$.ajax({
url: '/Profile/TranfareMoney',
type: 'POST',
data: { ToUsername: userName, Amount: amount },
dataType: 'json',
success: function (result) {
$('#transfare_error_list').html(result.text);
$('#trans_verification_id').val(result.id);
$('#transfare_username').val("");
$('#transfare_amount').val("");
},
error: function () {
$('#transfare_error_list').html('Oops... Error.');
}
});
}
});
I'm not 100% sure, but shouldn't you controller action handler be public ?

Resources