ViewModel - repopulate form with new content after ajax requests - c#

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

Related

Received NULL Object in Controller when send request from view ( Ajax) even I use [FromBody] C#

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

MVC: When returning from the controller on Ajax call, the result is undefined

I'm making an Ajax call to the controller when clicking on a Kendo button and return the model:
#(Html.Kendo().Button()
.Name("btnSubmit")
.HtmlAttributes(new { type = "button" })
.Icon("rotate")
.Content("View Details"))
<script>
$("#btnSubmit").click(function () {
$.ajax({
url: "/MyController/MyMethod/",
type: 'post',
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (result) {
window.location.href = "#Url.Action("RedirectToView", "MyController", new { myModel = "data" })".replace("data", result);
}
})
});
</script>
The controller's method returns the model:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult MyMethod()
{
var reportDate = Session["FileDate"] == null ? DateTime.Now : Convert.ToDateTime(Session["FileDate"].ToString());
var myModel = new MyModel();
myModel.ColOfData = myModel.GetColOfData(reportDate);
return Json(myModel, JsonRequestBehavior.AllowGet);
}
When I debug my Ajax function, result is undefined. The result should be assigned to MyModel, since I'm returning the model back to an Ajax function. I need to pass that result to another method in the controller that would return my Partial View containing the Grid:
public ActionResult RedirectToView(MyModel myModel)
{
return PartialView("_MyPartialView", myModel);
}
What am I doing wrong?
Your problem isn't related to kendo.
From your controller you have to return a json object like this
return Json(new {result=myModel});
And in your ajax result you will have your entire model.
After that from the code you provided I am afraid you can't pass your entire model in the url of your GET.
You could probably pass the model Id like that
window.location.href = "#Url.Action("RedirectToView", "MyController", new { id= "modelId" })".replace("modelId", result.Id);
And make your action something like that
public ActionResult RedirectToView(string id){
// Get the model data you want .....
return PartialView("_MyPartialView", myModel);
}

Pass whole Model through ajax call

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

Return view with ViewModel after ajax call

i call an action from ajax function, get my ViewModel in it and then try to open new view with other ViewModel but redirectToAction and return view aren't working. Other answers i saw only got to opening other view without sending ViewModel with it
ajax call
$("#delete").click(function () {
var model = $("#forma").serialize();
console.log("delete", model);
$.ajax({
url: '#Url.Action("DeleteDevices", "package")',
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: model,
success: function (result) {
}
});
return false;
});
and contorller which does nothing
public ActionResult DeleteDevices(PackageDevicesViewModel viewModel)
{
//model processing here
return View(NewModel);
}
change
data: model,
to
data: JSON.parse(JSON.stringify($("form").serializeArray()))

JSON and ASP.NET MVC

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

Categories