发布到MVC4中的控制器

Posting to a controller in MVC4

本文关键字:控制器 MVC4      更新时间:2023-09-26

我在这里问了几个问题,但没有任何可行的答案。我可能走错了路,或者问错了。基本上,我想做的是在页面中加载VAR:

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

然后用jQuery和JavaScript操作反映原始模型的testModel属性,然后用AJAX请求将其发布回控制器方法:

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

控制器:

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

如有任何帮助,我们将不胜感激。

我已经尝试了下面其他人的建议,但交易始终无法到达控制器方法。为什么不呢?

Ajax类型指定请求的类型。(获取或发布)详细信息

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

type表示您正在进行的请求类型,而不是要返回的数据类型。dataType是应该有的,POSTtype字段中。

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

基本上你是通过javascript发布数据的,所以如果成功,你需要一个Json对象来解析所以你需要return Json(model):

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

并且您的JS为:

 $.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
              })
        })

其中key将是您的Model Property name,val将分别是其值


现在消除您的困惑"何时返回View?"在ASP.NET MVC中,有三种方法可以将信息从控制器传递到视图我们使用Html助手生成Html字段,并将它们与模型绑定Get/Post从视图到控制器的数据值

  • 作为强类型模型对象。(针对特定型号)
  • 作为动态类型(使用@model dynamic)
  • 使用ViewBag

现在,当您使用html助手时,您可以返回带有传递的对象模型的视图,它将自动将视图中的数据填充为:

强类型模型对象

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

将视图渲染为

Return View("your View Path", modelObject)

以下是我为使这种方法发挥作用所做的:

在页面(.cs.html)中:

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

然后在控制器中:

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

这运行得很好,在我看来,这是大多数使用MVC4及以上版本的应用程序的发展方向。通过这种方式,整个模型都在页面中,可以很容易地使用jQuery和JavaScript进行操作,然后发送到控制器进行处理。这甚至可以是一个大型复杂的模型,我已经尝试过了。不再有回帖、页面闪烁和重写。。。