MVC4 Ajax- Pass complete model to controller - ajax

I have my AJAX call
$.ajax({
type: 'post',
url: "/Store/LoadStoreIndex",
data: , //Entire Model Here!!
dataType: "text",
success: function (result) {
$('#Postback').html(result);
}
});
I need to send my entire model back to the controller, but after much searching can't find anything ... Can somebody show me what I need to be doing?

Controller Get Action
public ActionResult Index(YourModel model)
{
YourModel model = new YourModel();
return View(model);
}
View
#model YourModel
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "form1" }))
{
#Html.TextBoxFor(x => x.EmailAddress)
#Html.TextBoxFor(x => x.Name)
...
}
Script
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
// you can post your model with this line
data: $(this).serialize(),
beforeSend: function () {
},
complete: function () {
},
success: function (result) {
},
error: function () {
}
});
}
return false;
});
});
Controller Post Action
[HttpPost]
public ActionResult Index(YourModel model)
{
return View();
}

Related

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 PostBack: Read data from Controller

How do I read the data from my controller in my ajax postback?
I have a Razor form
#using (Html.BeginForm("CreateDocument", "Pages", FormMethod.Post, new { id = "createDocumentForm" }))
{
....
}
And I catch the Submit action in JavaScript:
<script type="text/javascript">
$(document).ready(function () {
$("#createDocumentForm").submit(
function () {
showWaitMode();
$.ajax({
data: ("#createDocumentForm").serialize,
success: (e) => {
console.log(e);
},
error: (errorResponse) => {
alert(errorResponse)
}
})
return false;
}
);
});
</script>
In my controller I hit this method:
public ActionResult CreateDocument(NotatFletModel model)
{
var reuslt = new
{
Staus = true,
GoDocumentId = model.ContactId.ToString(),
ErrorMessage = model.DocumentKindId,
};
return Json(reuslt);
}
But in my Ajax success function I would like to get the data from my contorller. I expected it to be in my parameter e but it's not
So in short: How do I do an Ajax post and read the data posted back from the controller
Checkout my code for Form Post using ajax
Html :
#using (Html.BeginForm("CreateDocument", "Pages", FormMethod.Post, new { id = "createDocumentForm" }))
{
....
}
Jquery :
$("#createDocumentForm").submit(
function (e) {
showWaitMode();
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
url: url,
type: 'POST',
data: form.serialize(), // serializes the form's elements.
success: function (data) {
console.log(data); // show response
},
error: (errorResponse) => {
alert(errorResponse)
}
})
return false;
}
);
Controller :
//You can Use FormCollection also to get data
//public ActionResult CreateDocument(FormCollection fc) {
[HttpPost]
public ActionResult CreateDocument(NotatFletModel model) {
//your logic
return Json(model, JsonRequestBehavior.AllowGet);
}

Jquery select2 plugin with asp.net mvc4 and ajax

I am trying to populate data into Select2 dropdown using JSON which is returned by a controller class.But it is not working.There is no error.Here is the code
client Side
$("#products").select2({
minimumInputLength: 2,
ajax: {
url: "Search",
dataType: 'json',
type: "POST",
quietMillis: 50,
data: function (term) {
return {
"q": JSON.stringify(term),
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
}
}
});
Controller Action
[HttpPost]
public JsonResult Search(string q)
{
//testing data
return Json(new products() {id = "2", text = "biotouch"});
}
Product class
public class products()
{
public string id{get;set;}
public string text{get;set;}
}
It worked when I changed
results: function (data) {
to
ProcessResults: function (data) {
$("#products").select2({
minimumInputLength: 2,
ajax: {
url: "YourControllerName/Search",
dataType: 'json',
type: "POST",
quietMillis: 50,
data: function (term) {
return {
"q": JSON.stringify(term),
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
}
}
});
I have added controller name in URL you forgot to add controller name in url.

Pass action with model to jquery ajax success call

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

How to post various custom data types using Ajax in MVC3?

I have this ViewModel to represent each Category and it's several Sub-Categories in my project:
public class Categories
{
//a simple string for the category name
[Required]
public string Cat_Name { get; set; }
//a list of strings for the sub-categories
public List<string> SubCat_Name { get; set; }
}
I pass this model to the view, and I use it to construct my form like this:
#using (Html.BeginForm("Category", "Admin", FormMethod.Post))
{
#Html.TextBoxFor(m => m.Name, new { #class = "Cat" })
#Html.TextBoxFor(m => m.SubName, new { #class = "Sub" })
#Html.TextBoxFor(m => m.SubName, new { #class = "Sub" })
#Html.TextBoxFor(m => m.SubName, new { #class = "Sub" })
#Html.TextBoxFor(m => m.SubName, new { #class = "Sub" })
<input type="button" value="Create New Category" name="Category" onclick="DoIt()" />
}
And as you see, the javascript function "DoIt()" is called by the click on the input button.
here's the function :
function DoIt() {
var stringArray = new Array();
//I put all of the sub-categories inside an array, to be like a list<string>
$(".Sub").each(function (index, value) {
stringArray[index] = this.value;
});
$.ajax({
url: '/Admin/Category',
type: "POST",
data: JSON.stringify($(".Cat").attr("value") , stringArray),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () { console.log("post done"); },
error: function () { }
});
}
As you can see, in the ajax method I'm trying to pass the "Category Name" $(".Cat").attr("value") and it's "Sub-Category Names" stringArray to the corresponding action method which requires Categories datatype I created as a viewmodel before. It looks like this:
public ActionResult Category(Categories CAT)
{
//Do something
return View();
}
The problem is the ajax method can't post two datatypes at once, or just that I don't know how to do it.
I also tried this :
var postdata = {
Name: $(".Cat").attr("value"),
SubName: stringArray
};
and put postdata inside the JSON.stringify() instead. But still nothing is passed to the action method.
I think you are very close.
Try this
var postdata = {
Cat_Name: $(".Cat").val(),
SubCat_Name: stringArray
};
&
$.ajax({
url: '/Admin/Category',
type: "POST",
data: JSON.stringify(CAT:postdata),
dataType: "json",
contentType: "application/json",
success: function () { console.log("post done"); },
error: function () { }
});
Try to send data formatted like this:
$.ajax({
url: '/Admin/Category',
type: "POST",
data: JSON.stringify({ Cat_Name: $(".Cat").val(), SubCat_Name: stringArray }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () { console.log("post done"); },
error: function () { }
});

Resources