简体   繁体   中英

Posting to a controller in MVC4

I have asked a few questions here without any workable answers. I may have been on the wrong track or asked it all wrong. Basically, what I am trying to do is load up a VAR in the page:

 var testModel = @Html.Raw(JSON.Encode(Model))

Then manipulate the testModel properties, which reflect the original model, with jQuery and JavaScript, then post it back to a controller method with an AJAX request:

 $.ajax({
   datatype: 'json',
   data: testModel // ?? or some other way?
    // etc
 });

The controller:

 public ActionResult PostModel (ModelName model)  // or JsonResult
 {
     //do things
     return Json(model);  // or return View?
 }

Any help would be appreciated.

I have tried what others have suggested below, and still the transaction never makes it to the controller method. Why not?

Ajax type Specifies the type of request. (GET or POST) DETAILS

$.ajax({
   type: 'POST',//or GET
   dataType: 'json',
   data: testModel // ?? or some other way?
    // etc
 });

type represents the type of request you're making not the type of data you're going to get back. dataType is what you should have there and POST in the type field.

 $.ajax({
   type: 'POST',
   dataType: 'json',
   data: testModel // ?? or some other way?
    // etc
 });

Basically you are posting the data through javascript so on success you need a Json object to parse so you need to return Json(model) :

public ActionResult PostModel (ModelName model)  // or JsonResult
 {
     //do things
     return Json(model);  
 }

and your JS as:

 $.ajax({
   type: 'POST',
            url: '{somecontroller}/{someaction}',
            cache: false,
            contentType: 'application/json; charset=utf-8',
            data:testModel, 
            success: function (object) {
                $.each(object, function (key, val) {
                  //do your stuff here
              })
        })

Where the key will be your Model Property name and val will be its value respectively


Now to remove your confusion "When to return View?" There are three ways to pass information from a controller to a view in ASP.NET MVC. We use Html helpers to generate html fields and bind them with models to Get/Post the data values from view to controller

  • As a strongly typed model object. (for specific model)
  • As a dynamic type (using @model dynamic)
  • Using the ViewBag

Now when you are using the html helpers you can return view with the object model passed with it, which will automatically populate the data in your view as:

Strongly typed model object

<%@ Page Title="#" Language="VB" MasterPageFile="#" Inherits="System.Web.Mvc.ViewPage(Of somemodel)" %>

Render view as

Return View("your View Path", modelObject)

Here's what I did to make this approach work:

In the page (.cshtml):

 function SendJsonData() {
     localModel.itemNumber = $("#txtItemNumber").val();
     //  etc for the rest of the fields
     $.ajax({
        url: '@Url.Action("PostModel", "ItemControl")',
        data: JSON.stringify(localModel),
        dataType: 'json',
        cache: false,
        type: 'POST',
        contentType: 'application/json, charset=utf-8',
        success: function(data) {
            //do stuff
        },
        error: function () {
           alert('error');
        }
      });

Then in the controller:

      [HttpPost]
      public JsonResult PostModel(ItemModel localModel)
      {
          //do stuff with data model
          return Json(localModel);
      }

This worked fine and seems to me to be the way to go for most applications using MVC4 and above. This way the entire model is in the page and can be readily manipulated with jQuery and JavaScript then sent to the controller for processing. This can even be a large complex model, I've tried it. No more post backs and page flicker and rewriting...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM