如何将javascript对象传递给C#MVC 4控制器 [英] How to pass a javascript object to a C# MVC 4 controller

查看:531
本文介绍了如何将javascript对象传递给C#MVC 4控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MVC4中,如何将javascript对象传递给AJAX中的C#控制器?
最后我尝试了这个但是没有用。

In MVC4, how do you pass a javascript object to a C# controller in AJAX? Finally I tried this but it did not work.

Javascript客户端:

    var myData = {Propr1: '', Propr2: ''};
    $.ajax({
        type: 'POST',
        data: JSON.stringify(myData),
        url: '/Home/SubmitMyData',
        contentType: 'application/json',
        dataType: 'json',
        success: alert('Youhou'),
        error: alert('not good')
    });

C#服务器端方法:

    public ActionResult SubmitMyData(MyParamModel myParam)
    {
        // Do my stuff here with my parameter
        return View();
    }

    public class MyParamModel
    {
        string Prop1 { get; set; }
        string Prop2 { get; set; }
    }

我的参数始终为空。我试图更改contentType但它仍然无法正常工作。
我的错误在哪里?我发现了一些帖子,但我没有找到我做错的事。

My parameter is always null. I tried to change the contentType but it still not work. Where are my mistakes? I found some posts but I did not find what I did wrong.

非常感谢。

推荐答案


  1. 确保javascript和C#模型之间的属性名称匹配。在你的问题中,javascript对象有 Propr1 Propr2 ,但在C#模型中你有 Prop1 Prop2 (缺少r)。

  2. 不要 stringify 发送前的数据,不要将 dataType 设置为 json 。 MVC可以使用一组post参数解析,而不需要代码中的json序列化。

  3. 省略 contentType ,它不是必要。 WebAPI应该自动检测这个。你可以离开它,但这是无关紧要的。

  4. 确保模型属性是公开的。

  1. Make sure the property names match between the javascript and the C# model. In your question you had Propr1 and Propr2 for the javascript object, but in the C# model you had Prop1 and Prop2 (missing the "r").
  2. Do not stringify the data before sending it, and do not set dataType to json. MVC can parse just fine with a collection of post parameters without the json serialization in your code.
  3. Omit the contentType, it is not necessary. WebAPI should autodetect this. You can leave it, but it's extraneous.
  4. Make sure the model properties are public.

Javascript客户端:

    var myData = {Prop1: '', Prop2: ''}; // #1
    $.ajax({
        type: 'POST',
        data: myData, // #2
        url: '/Home/SubmitMyData',
        //contentType: 'application/json', #3
        //dataType: 'json', #2
        success: alert('Youhou'),
        error: alert('not good')
    });

C#服务器端方法:

    public ActionResult SubmitMyData(MyParamModel myParam)
    {
        // Do my stuff here with my parameter
        return View();
    }

    public class MyParamModel // #4
    {
        public string Prop1 { get; set; }
        public string Prop2 { get; set; }
    }

这篇关于如何将javascript对象传递给C#MVC 4控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆