传递JSON数据到一个控制器方法,而不必声明一个对象 [英] Passing JSON Data Into A Controller Method Without Having To Declare An Object

查看:183
本文介绍了传递JSON数据到一个控制器方法,而不必声明一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET MVC和jQuery保存一些数据通过AJAX调用。我现在通过使用像这样的jQuery的阿贾克斯()函数的一些JSON数据

  $。阿贾克斯({
    数据类型:JSON,
    输入:POST,
    网址:'@ Url.Action(UpdateName,编辑),
    数据:{
        编号:16,
        名称:约翰尼C.坏
    }
});

使用这种控制器的方法和辅助类。

 公共无效UpdateName(波科POCO)
{
    变种人= PersonController.GetPerson(poco.Id);
    person.Name = poco.Name;
    PersonController.UpdatePerson(人);
}公共类波科
{
    公众诠释标识{搞定;组; }
    公共字符串名称{;组; }
}

接受JSON数据的另一种方法是简单地使用多个参数是这样

 公共无效UpdateName(INT ID,字符串名称)
{
    变种人= PersonController.GetPerson(ID);
    person.Name =名称;
    PersonController.UpdatePerson(人);
}

这方法是确定的参数数量较少,但我的现实世界code通常已经有大约5 - 10个参数。使用一个对象,而不必声明和使用所有的这些参数是非常方便的。

我wondernig如果接受JSON数据作为单个对象,不必声明一个类为每个控制器方法,我想用这种方法的另一种方式。例如,像这样:

 公共无效UpdateName(动态someData)
{
    变种人= PersonController.GetPerson(someData.Id);
    person.Name = someData.Name;
    PersonController.UpdatePerson(人);
}


解决方案

可能的解决方法

创建特定型号的粘合剂,例如

     公共类DynamicModelBinder:DefaultModelBinder
    {
        公众覆盖对象BindModel(ControllerContext controllerContext,ModelBindingContext的BindingContext)
        {
            如果(controllerContext.HttpContext.Request.Form.AllKeys.Any(X =系列> X ==动态))
            {
                动态模型=新ExpandoObject();
                IDictionary的underlyingmodel =模型;                的foreach(在controllerContext.HttpContext.Request.Form.AllKeys VAR键)
                    underlyingmodel.Add(键,(bindingContext.ValueProvider.GetValue(键).RawValue作为字符串[])一());                回归模型;
            }            返回base.BindModel(controllerContext,BindingContext中);
        }
    }

这粘结剂将检查特定的输入名称为动态,然后创建动态对象

     公众的ActionResult指数()
    {
       返回查看();
    }    [HttpPost]
    公众的ActionResult指数(动态输入)
    {
       ViewBag.Result = input.phrase;
       返回查看();
    }

I'm using ASP.NET MVC and jQuery to save some data via AJAX calls. I currently pass in some JSON data using the jQuery ajax() function like so

$.ajax({
    dataType: 'json',
    type: 'POST',
    url: '@Url.Action("UpdateName", "Edit")',
    data: {
        id: 16,
        name: 'Johnny C. Bad'
    }
});

using this controller method and helper class.

public void UpdateName(Poco poco)
{
    var person = PersonController.GetPerson(poco.Id);   
    person.Name = poco.Name;
    PersonController.UpdatePerson(person);
}

public class Poco
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Another way of accepting the JSON data is to simply use multiple arguments like this

public void UpdateName(int id, string name)
{
    var person = PersonController.GetPerson(id);    
    person.Name = name;
    PersonController.UpdatePerson(person);
}

This approach is ok for a smaller number of arguments, but my real world code has usually has about 5 - 10 arguments. Using an object instead of having to declare and use all these arguments is very handy.

I'm wondernig if there is another way of accepting the JSON data as a single object and not having to declare a class for each controller method I want to use this approach in. For example, something like this:

public void UpdateName(dynamic someData)
{
    var person = PersonController.GetPerson(someData.Id);   
    person.Name = someData.Name;
    PersonController.UpdatePerson(person);
}

解决方案

Possible solution

Create specific model binder, for example as



    public class DynamicModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (controllerContext.HttpContext.Request.Form.AllKeys.Any(x => x == "dynamic"))
            {
                dynamic model = new ExpandoObject();
                IDictionary underlyingmodel = model;

                foreach (var key in controllerContext.HttpContext.Request.Form.AllKeys)
                    underlyingmodel.Add(key, (bindingContext.ValueProvider.GetValue(key).RawValue as string[]).First());

                return model;
            }

            return base.BindModel(controllerContext, bindingContext);
        }
    }

This binder will check for specific input with name "dynamic" then create dynamic object



    public ActionResult Index()
    {
       return View();
    }

    [HttpPost]
    public ActionResult Index(dynamic input)
    {
       ViewBag.Result = input.phrase;
       return View();
    }

这篇关于传递JSON数据到一个控制器方法,而不必声明一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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