Is it possible to pass a whole Model through my jQuery's ajax call?
For know I can only get it working if i set one variable at the time.
As the code shows I pass the iVideo_ID through the ajax call. The Video object has a lot of other fields. So instead of writing all the attributes, can i pass the whole existing object (Video Model)?
$.ajax({
type: "POST", //HTTP POST Method
url: "/Video/UpdateComment", // Controller/View
data: { //Passing data
iVideo_ID: '#(Model.Video.iVideo_ID)'
}
});
I have tried with this but it just return a Model that is null:
$.ajax({
type: "POST", //HTTP POST Method
url: "/Video/NyMetode", // Controller/View
data: '#(Model)'
});
So how can i pass the whole model? Is it possible?
EDIT:
My View Model I try to pass:
public class CommentViewModel
{
public List<Comments> Comments { get; set; }
public List<Tasks> Tasks { get; set; }
public Videos Video { get; set; }
public List<VideoTaskScores> VideoTaskScores { get; set; }
}
actually ya you can do that
just change around a bit for more simplification I.e
<script>
var jsonData= #html.raw(json.encode(Model));
then in ajax data
data: modelName : jsonData,
just make sure in your actionresult the param name is also modelName ie
public ActionResult ActionName(model modelName)
Try something like this in your cshmtl page :
<script type="text/javascript">
function GetModel() {
return #Html.Raw(Json.Encode(Model));
}
</script>
And this how you can send WHOLE model:
var ModelData = GetModel();
$.ajax(
{
type: "POST", //HTTP POST Method
url: "/Video/UpdateComment", // Controller/View
data: { ModelName: GetModel(); }
});
You can embed the model properties within a form and then serialize the form and pass it your ajax call.
$.ajax({
url: "/Controller/ActionName",
type: 'POST',
data: $('#MyFormName').serialize()
})
.done(function (response) {
alert(response.Message);
}
}).fail(function () {
alert(Something went wrong);
});
And in the action you can directly access your model as
public ActionResult ActionName(MyModel modelObj)
{}
You can use Json.stringify(model) but before implement this you you should get your Lists of model class with their last states by using jQuery.
Can you try this
// you can get your model data from view by jQuery
// your model has list objects so you should get these from view and add these into model
var model = {...}; // your object corresponds model object
$.ajax({
type: "POST", //HTTP POST Method
url: "/Video/UpdateComment", // Controller/Action
data: Json.stringify(model),
contentType: "application/json"
}).done(function (res) {
// after done insert your code here
});;
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;
....
}
This is my DisputeController method stub:
[HttpPost]
public virtual ActionResult UpdateDisputeStatus(DisputeUdpateStatusModel model)
{//some code
Here is my Ajax call:
var url = '/dispute/UpdateDisputeStatus';
var disputeStatusObj = {
DisputeId: id,
DisputeStatusId: selectedValue
}
$.ajax({
url: url,
cache: false,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: disputeStatusObj,
success: function (data) {
alert('Status Changed Successfully');
},
error: function (e) {
alert('Error: ' + e.status);
}
});
I know the routing works, as without using the data parameter the code enters my method (obviously without the model in parameters)
I have tried the following data formats:
data: {'DisputeId': DisputeId, 'StatusId': DisputeStatusId},
data: {disputeStatusObj},
data: JSON.Stringify(disputeStatusObj)
using controller methods:
[HttpPost]
public virtual ActionResult UpdateDisputeStatus(string disputeId, string statusId)
[HttpPost]
public virtual ActionResult UpdateDisputeStatus(modelname model)
None of which work. I get Not found errors or 500's.
Bearing in mind that I know the routing is correct, when I send the request with no data, so what am I missing here?
Am I declaring the controller incorrectly?
Verify your model that should be the same name as well as the data type because of while post the value from Jquery that values are not mapping with the property of the model.
#Mike I tried below code
public class DisputeUpdateStatusModel
{
public string DisputeId { get; set; }
public string DisputeStatusId { get; set; }
}
public class DisputeController : Controller
{
[HttpPost]
public virtual ActionResult UpdateDisputeStatus(DisputeUpdateStatusModel model)
{
return new ContentResult() { Content = "OK" };
}
}
script on view as:
<script type="text/javascript">
var disputeStatusObj = {}
disputeStatusObj.model = {
DisputeId: 1,
DisputeStatusId: 1
}
var url = '/dispute/UpdateDisputeStatus';
$.ajax({
url: url,
cache: false,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(disputeStatusObj),
success: function (data) {
alert('Status Changed Successfully');
},
error: function (e) {
alert('Error: ' + e.status);
}
});
</script>
Please see.
If this is not working, can you please show Model class?
thanks for all your input. My solution was a combination of the answers above.
I was unable to get my code to model bind, so I went back to basics.
I took out the contentType: "application/json; charset=utf-8", as suggested by Stephen Muecke, and ditched the model in my controller and replaced it with string disputeId, string statusId and as suggested by Er Pravin Suthar ensured the parametes were called the same thing. Also to note, the data section was sent as data: { disputeId: disputeId, statusId: statusId } with no quotes around the parameter names. So I ended up with:
var statusId = statusDropdown.value;
var disputeId = $("#disputeId").val();
$.ajax({
url: "/Dispute/UpdateDisputeStatus",
data: { disputeId: disputeId, statusId: statusId },
type: 'POST',
success: function (data) {
alert('Success');
},
error: function (e) {
alert('Status not changed' + e.responseText + ' : ' + e.status);
}
});
and the Controller structure is:
[HttpPost]
public virtual ActionResult UpdateDisputeStatus(string disputeId, string statusId)
Thanks Again for all your input!
Currently I can to create models regularly (by going SettingProfile/Create)
But when I try to use AJAX to send data wrapped in settingProfile JS object it returns HTTP 500 Internal Server Error error, I believe problem is in the data type. What would be correct way of calling Create method in AJAX?
My code:
Model:
public class SettingProfile
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public string Name { get; set; }
public long? UserId { get; set; }
public string Url { get; set; }
}
View (JS):
function saveSettingProfile() {
var name = prompt("Please enter profile name", "");
var url = $("form").serialize(); // Not AJAX url, its a variable in model
var settingProfile = {
Name: name,
Url: url
};
jQuery.ajax({
url: "#Url.Action("Create", "SettingProfile")",
contentType: "application/json; charset=utf-8",
dataType: "json",
method: "POST",
data: settingProfile
}).done(function (response) {
alert("Profile saved successfully");
}).fail(function () {
alert("Could not save profile");
});
}
Controller:
[HttpPost]
//[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Name,Url")] SettingProfile settingProfile)
{
settingProfile.UserId = 8; // TODO: get user id from session
if (ModelState.IsValid)
{
db.SettingProfiles.Add(settingProfile);
db.SaveChanges();
return Json(new { success = true });
}
return Json(new { success = false });
}
500 error means, your server code is crashing. It could be of many reasons. One thing i noticed (which might cause a 500 error) is the way you are sending data.
You specified the contentType as "application/json" .But you are sending the javascript object as it is. So your request payload will be sent as something like
Name=SomeNameValue&Url=SomeUrlValue And with your current server code, the model binder cannot map it to an object of SettingProfile.
The solution is to send the stringified version of your javascript object. You may use the JSON.stringify method to do so.
jQuery.ajax({
url: "#Url.Action("Create", "SettingProfile")",
contentType: "application/json; charset=utf-8",
method: "POST",
data: JSON.stringify(settingProfile)
}).done(function (response) {
alert("Profile saved successfully");
};
Now your client code will send a request payload like
{"Name":"SomeName","Url":"SomeUrl"}
and model binder will be able to map it properly.
If it is simple data, you can simply not mention a custom contentType and send the js object as it is. jQuery will use the default contentType value which is "application/x-www-form-urlencoded" and model binding will work.
So the below code will work fine.
jQuery.ajax({
url: "#Url.Action("Create", "SettingProfile")",
method: "POST",
data:settingProfile
})
You may also check the browser's network tab and see the response coming back from the server for that ajax call. If an exception happens, you can see the details there.
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"
});