asp.net mvc操作方法未收到json数据

发布于 2024-11-01 00:19:09 字数 2312 浏览 1 评论 0原文

我正在尝试从客户端脚本获取一些数据到控制器,我正在对我的数据进行字符串化,因此我收到类似以下内容:

{"Name":"","Description":"","FieldType":"radio","Fields":[{"Field":{"Name":"something","Value":"nameit"}},{"Field":{"Name":"something else","Value":"dontnameit"}}]}

我需要在控制器上验证我的数据,但是,在我的操作中,由于某种原因我收到一个空值,如果我使用对象或字符串?这是为什么?

我查看了很多其他帖子,但不清楚,我是否需要创建自己的自定义 IValueProvider 实现?我认为 ms futures assembley 中有一个可用的文件,我试图找到该文件,因为我不想要 dll 内的所有代码,但我找不到它...

任何指针将不胜感激...

控制器:

[HttpPost]
public JsonResult AddField(string field) //or object
{
//code here
}

编辑:我关注了 phill haack 的帖子,但实际上将强类型对象返回到我的视图时遇到了一些错误...

我的 ajax 调用..

{
        url: url,
        type: "post",
        dataType: 'json',
        traditional: true,
        data: jsondata, // { "field" : jsondata},
        contentType: 'application/json; charset=utf-8',
...
}

我创建了一个自定义值提供程序...

public class Jsonify : ValueProviderFactory { 公共 Jsonify() { }

    public override IValueProvider GetValueProvider(ControllerContext controllerContext)
    {
        var jsonData = GetDeserializedJson(controllerContext);
        if (jsonData == null)
        {
            return null;
        }

        //currently used by mvc2 futures
        //return new DictionaryValueProvider<object>(backingStore, 
        //CultureInfo.CurrentCulture);
        // what do I return?

    }
private static object GetDeserializedJson(ControllerContext controllerContext)
        {
            if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
            {
                // not JSON request
                return null;
            }

            StreamReader reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
            string bodyText = reader.ReadToEnd();
            if (String.IsNullOrEmpty(bodyText))
            {
                // no JSON data
                return null;
            }

            //json.net
            var jsonData = JsonConvert.DeserializeObject<SurveyField>(bodyText);
            return jsonData;
        }
}

控制器:

public JsonResult AddSimpleField(SurveyField field) {  ... }

I am trying to get some data to a controller from client side script, I am stringfying my data so I receive something like:

{"Name":"","Description":"","FieldType":"radio","Fields":[{"Field":{"Name":"something","Value":"nameit"}},{"Field":{"Name":"something else","Value":"dontnameit"}}]}

I will need to validate my data on the controller however, in my action I am recieving a null for some reason, if I use object or string? Why is that?

I have had a look into a lot of other posts but it is not clear, do I need to create my own custom IValueProvider implementation? I think there is one available in the ms futures assembley, I tried to locate the file as I do not want all the code inside the dll, but I could not find it...

Any pointers would be appreciated...

Controller:

[HttpPost]
public JsonResult AddField(string field) //or object
{
//code here
}

Edit: I have followed the post by phill haack but had some errors actually returning the strongly typed object to my view...

my ajax call..

{
        url: url,
        type: "post",
        dataType: 'json',
        traditional: true,
        data: jsondata, // { "field" : jsondata},
        contentType: 'application/json; charset=utf-8',
...
}

I created a custom value provider...

public class Jsonify : ValueProviderFactory
{
public Jsonify() { }

    public override IValueProvider GetValueProvider(ControllerContext controllerContext)
    {
        var jsonData = GetDeserializedJson(controllerContext);
        if (jsonData == null)
        {
            return null;
        }

        //currently used by mvc2 futures
        //return new DictionaryValueProvider<object>(backingStore, 
        //CultureInfo.CurrentCulture);
        // what do I return?

    }
private static object GetDeserializedJson(ControllerContext controllerContext)
        {
            if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
            {
                // not JSON request
                return null;
            }

            StreamReader reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
            string bodyText = reader.ReadToEnd();
            if (String.IsNullOrEmpty(bodyText))
            {
                // no JSON data
                return null;
            }

            //json.net
            var jsonData = JsonConvert.DeserializeObject<SurveyField>(bodyText);
            return jsonData;
        }
}

Controller:

public JsonResult AddSimpleField(SurveyField field) {  ... }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

执笔绘流年 2024-11-08 00:19:09

您可以查看 以下博客文章说明了如何使用自定义 JsonValueProviderFactory 将 JSON 编码的字符串从客户端脚本发送到控制器操作,并让该操作将其作为强类型模型并受益于默认模型绑定器的验证:

[HttpPost]
public ActionResult AddField(SomeViewModel model)
{
    if (!ModelState.IsValid)
    {
        // the client sent an invalid data
        return Json(new { IsSuccess = false });
    }
    // the model passed validation => do some processing with this model
    return Json(new { IsSuccess = true });
}

正如 Phil Haack 所解释的那样,仅当您使用 ASP.NET MVC 2 并且内置 ASP.NET 时,才需要此自定义 JsonValueProviderFactory MVC 3,所以它应该开箱即用。

You may take a look at the following blog post which illustrates how you could use a custom JsonValueProviderFactory to send a JSON encoded string from client scripts to a controller action and have this action receive it as a strongly typed model and benefit from the validation of the default model binder:

[HttpPost]
public ActionResult AddField(SomeViewModel model)
{
    if (!ModelState.IsValid)
    {
        // the client sent an invalid data
        return Json(new { IsSuccess = false });
    }
    // the model passed validation => do some processing with this model
    return Json(new { IsSuccess = true });
}

As Phil Haack explains it this custom JsonValueProviderFactory is only necessary if you are working with ASP.NET MVC 2 and is built-in ASP.NET MVC 3 so it should work out of the box.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文