How do you return a serialized JSON object to the client side using ASP.NET MVC via an AJAX call?
From the controller you can just return a JsonResult:
public ActionResult MyAction()
{
... // Populate myObject
return new JsonResult{ Data = myObject };
}
The form of the Ajax call will depend on which library you're using, of course. Using jQuery it would be something like:
$.getJSON("/controllerName/MyAction", callbackFunction);
where the callbackFunction takes a parameter which is the data from the XHR request.
Depending on your syntax preferences, the following also works:
public ActionResult MyAction()
{
return Json(new {Data = myObject});
}
This is the Small block of code for just understand , how we can use JsonResults in MVC Controllers.
public JsonResult ASD()
{
string aaa = "Hi There is a sample Json";
return Json(aaa);
}
You can also System.Web.Script.Serialization; as below
using System.Web.Script.Serialization;
public ActionResult MyAction(string myParam)
{
return new JavaScriptSerializer().Serialize(myObject);
}
Ajax
$.ajax({
type: 'POST',
url: '#Url.Action("MyAction","MyMethod")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "myParam": "your data" }),
success: function(data)
{
console.log(data)
},
error: function (request, status, error) {
}
});
If you need to send JSON in response to a GET, you'll need to explicitly allow the behavior by using JsonRequestBehavior.AllowGet.
public JsonResult Foo()
{
return Json("Secrets", JsonRequestBehavior.AllowGet);
}
Related
Model:
public class From
{
public DateTime from { get; set; }
public DateTime to { get; set; }
}
Controller:
public MediaViewModel DashboardMediaByDate([FromBody] From y)
{ // some logic }
View:
<script>
$(function () {
// Get value on button click and show alert
$("#myBtn").click(function () {
var from = {
from: $("#from").val(), to: $("#to").val()
};
alert(from.from);
var y = JSON.stringify(from);
$.ajax({
type: "POST",
data: y,
dataType: 'json',
url: "/Queues/DashboardMediaByDate",
contentType: "application/json"
}).done(function (res) {
alert(res);
});
});
});
</script>
When I debug the request from browser :
Request Header
Payload
What I received in Controller:
Method Parameter
How can I send the object to controller from view model ?
Thanks in advance,
You can use the following AJAX call to get your data as required:
AJAX:
<script>
$(function () {
// Get value on button click and show alert
$("#myBtn").click(function () {
var from = {
from: $("#from").val(), to: $("#to").val()
};
alert(from.from);
$.ajax({
type: "POST",
data: {'json': JSON.stringify(from)},
dataType: 'json',
url: "/Queues/DashboardMediaByDate"
}).done(function (res) {
alert(res);
});
});
});
</script>
And your Controller method:
using System.Web.Script.Serialization;
[HttpPost]
public JsonResult DashboardMediaByDate(string json)
{
MediaViewModel myModel = new MediaViewModel();
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
var from = Convert.ToDateTime(jsondata["from"]);
var to = Convert.ToDateTime(jsondata["to"]);
//Your logic
return Json(new {myModel=myModel});
}
Changes from your original call:
Removed contentType from your AJAX call
Added [HttpPost] attribute on your Controller method
Removed [FromBody] attribute to get your data as a JSON string
Changed your data to send a JSON string instead of a Model
Once you get your data as a JSON string, you can de-serialize it your Model structure as required. I usually use this method when my Model does not have many properties.
You are using AJAX for your functionality which is generally used to update a portion of the page without reloading the entire page. If you want to redirect in the POST method from your Controller with a Model, then don't use ajax for your purpose. Alternatively if you know what to add to the view you return then handle the success callback and update the DOM.
You can access the above Model in your success method inside your AJAX like this:
success: function(data) {
//Get your model here
console.log(data.myModel);
}
I am using .Net Core 2.1. This is the function that takes the value of the input boxName from the user and is supposed to pass it to the controller - Create function when the "save button" is clicked.
<script type="text/javascript">
function Submit() {
var boxName = $("#boxID").val();
alert(boxName);
UNTIL HERE EVERYTHING IS FINE - THE ALERT RETURNS THE CORRECT VALUE
$.ajax({
type: "POST",
contentType: "application/json",
url: '/Box/Create',
datatype: 'json',
data: JSON.stringify({ ID: "#Model.Id", BoxName: boxName }),
success: function (response) {
alert("Box created");
}
error: function (response) {
alert("error");
}
});
}
IN THE CONTROLLER
public ActionResult Create(int ID, string BoxName)
{
Box _Box = new Box();
_Box.Name= BoxName;
_db.Boxes.Add(_Box);
_db.SaveChanges();
return RedirectToAction("Index");
}
THE STRING BoxName RECEIVED AS A PARAMETER FROM THE AJAX IS NULL
I even tried
public ActionResult Create([Bind(Include = "ID,BoxName")] Box Box)
but it didn't work either. The error was
Include is not a valid named attribute argument
Any help is appreciated.
Remove the content Type and don't use stringify. So your ajax call becomes
$.ajax({
type: "POST",
url: '/Box/Create',
datatype: 'json',
data: { ID: "#Model.Id", BoxName: boxName },
success: function (response) {
alert("Box created");
}
Edit: This is partially wrong though you should do it for clarity. If there is only one action and the verb is not specified in your controller, the action is done anyway regardless if it's POST or GET.
You are using a POST verb in your ajax, by default all actions in the controller are GET. Add the [HttpPost] attribute above your controller action.
[HttpPost]
public ActionResult Create(int ID, string BoxName)
{
...
}
You should create a binding from the body of the request : ie:
class CreateBinding {
public string ID { get; set;}
public string BoxName { get; set; }
}
And in you controller:
[HttpPost]
Public ActionResult Create([FromBody] CreateBinding binding)
{
var id = binding.ID;
var name = binding.BoxName;
....
}
>
I .net core 2.2 This is the object Object:
[Serializable]
public class oob
{
public int i { get; set; }
public string j { get; set; }
}
this is the action in "Home" Controller named Gett that takes oob as input from ajax
[HttpGet]
public IActionResult Gett(oob ww)
{
return Ok(ww);
}
Ajax
{
$.ajax({
type: "Get",
url: "Home/gett",
data: { ww: JSON.stringify({i:55,j:"weqe"})},
dataType: "json",
contentType:"json",
success: function (f) {
console.log(f);
},
error: function (f) {
console.log(f);
}
});
});
When request is made ,at the Gett(oob ww) i get an object with value of i=0 and j=null
Ideally you should not pass object to a GET request, for posting object, you should use POST.
If you still want, you need to change your GET method like following using FromQuery.
[HttpGet]
public IActionResult Gett([FromQuery] oob ww)
{
return Ok(ww);
}
And change your AJAX call like following.
$.ajax({
type: "Get",
url: "Home/gett",
data: {i:55,j:"weqe"},
dataType: "json",
contentType:"json",
success: function (f) {
console.log(f);
},
error: function (f) {
console.log(f);
}
});
Note: To pass the object you don't need JSON.stringify if you are using FromQuery for your API
When I call an AJAX Get/Post, I can send a ViewModel of my form to my Controller methods. Is there a way to repopulate the form after this request with the new values of the ViewModel? What the right return of my method: a Json with the ViewModel or a View? Like this:
$.ajax({
dataType: "JSON",
data: $('#form').serialize(),
type: "GET",
url: "SomeController/doSomething",
success: function(myViewModel) {
// How to repopulate my form with the new values?
}
});
public class SomeController {
[HttpGet]
public ActionResult DoSomething(MyViewModel model) {
model.SomeProperty = "This property needs to be changed into the View.";
// The right way is returning a Json with the ViewModel...
return Json(model, JsonRequestBehavior.AllowGet);
// or return some View?
return View(model);
}
}
What will be returned is HTML. Can I suggest that you return a PartailView(model), this way it can be used throughout the system, you do not need to json encode it just use return PartialView(model). Put the Partial View in your Shared Folder.
public ActionResult DoSomething(MyViewModel model) {
model.SomeProperty = "This property needs to be changed into the View.";
return PartialView("MyPartialView", model);
}
Change the ajax to stringify the form, this will allow the model binding to work:
$.ajax({
dataType: "JSON",
data: JSON.stringify({model : $('#form').serialize() }),
type: "GET",
url: "SomeController/doSomething",
success: function(myViewModel) {
$('#myUlDropDownListID').replaceWith(myViewModel);
}
});
In your ajax you need to replace the HTML with the return, in this case you have called in myViewModel. I.e. if it is a table then you would do
$('#myUlDropDownListID').replaceWith(myViewModel);
This will replace the table with the new HTML
I am having problems passing a javascript array to an MVC3 controller, not sure what I am doing wrong but this code does work with standard WCF service.
$(function () {
$("button").click(function () {
Poster();
});
});
function Poster() {
var data = [];
data.push(new WidgetProperty("test1", "value1"));
alert(data.length);
$.post("Home/Test", {test : data});
}
function WidgetProperty(name, value) {
this.Name = name;
this.Value = value;
}
and controller is
[HttpPost]
public ActionResult Test(WidgetProperty[] test)
{
return View("About");
}
public class WidgetProperty
{
public string Name { get; set; }
public string Value { get; set; }
}
Any ideas why the object that comes to the controller has null values for the properties? Checked with fiddler and it appears it passing the correct values.
Thanks!
You should use JSON.stringify() on your data before you post it, and since you know the data type is JSON, it is best to specify that the data being posted is JSON.
$.post("Home/Test", {test : JSON.stringify(data) }, "json");
Live DEMO
Edit:
I researched this a little more and it seems that you need to include contentType: "application/json" in order for this to work in mvc3:
$.ajax({
type: "POST",
url: "Home/Test",
data: JSON.stringify(data),
success: function(data){},
dataType: "json",
contentType: "application/json"
});