ASP.NET MVC - 从查询字符串获取对象列表

发布于 2024-11-24 09:01:47 字数 541 浏览 2 评论 0原文

我传递了一个参数列表。例如“名称”、“ID”、“类型”。 url 中会有很多这样的参数,如下所示:

"Name=blah1,Id=231,Type=blah1;Name=blah2,Id=2221,Type=blah1;Name=blah3,Id=45411,Type=blah3;"

我想知道是否有一种方法可以将这些查询参数映射到对象列表。因此,我可以创建一个对象:

MyTestObject {Name;Id;Type},并且可以说在我的控制器

Index(IList<MyTestObject> params)

参数中将填充查询字符串中的数据。

类似于 http://haacked. com/archive/2008/10/23/model-binding-to-a-list.aspx

I'm passed a list of parameters. Such as "Name", "Id", "Type". There will be an many of these in url, like so:

"Name=blah1,Id=231,Type=blah1;Name=blah2,Id=2221,Type=blah1;Name=blah3,Id=45411,Type=blah3;"

I wonder if there is a way to map these query parameters to a List of objects. So, I can create an object:

MyTestObject {Name;Id;Type} and can say in my controller

Index(IList<MyTestObject> params)

params will be filled in with data from query string.

Something that is similar to http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

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

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

发布评论

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

评论(5

凉墨 2024-12-01 09:01:47

实际上,我遵循了 Haack 先生的文章中的建议 我创建了一个类,其中所有参数都作为公共属性。然后我有一个视图获取该类型的对象列表。如果查询参数名称遵循某种模式(以索引为前缀),那么我会得到自动填充的对象列表,并且根本不需要进行任何手动解析。这对我来说是最简单的解决方案。

示例:

查询参数对象:

public class QueryParams
{
   public string Id,
   public string Name,
   public string Type
}

在控制器方法中:

public ActionResult Index(IList<QueryParams> queryData)

然后我确保查询字符串的格式如下(以索引开头):

http://localhost/myapp/?[0].id=123&[0].Name=blah&[0].Type=Person&[1].Id=345&[1].Name=示例&[1].Type=Stuff

在我的控制器中,queryData 列表参数将包含两个填充了正确数据的对象。

I actually followed advice in the article by Mr. Haack I created a class with all of the parameters as public properties. Then I had a view take a list of objects of that type. If the query parameter names follow a certain pattern (prepended by index) then I get a list of my object automatically populated and I don't have to do any manual parsing at all. This is the simplest solution for me.

Example:

query param object:

public class QueryParams
{
   public string Id,
   public string Name,
   public string Type
}

in controller method:

public ActionResult Index(IList<QueryParams> queryData)

then I make sure that query string is formated in the following way(prepended by index):

http://localhost/myapp/?[0].id=123&[0].Name=blah&[0].Type=Person&[1].Id=345&[1].Name=example&[1].Type=Stuff

In my controller, queryData list parameter will contain two objects populated with correct data.

晨与橙与城 2024-12-01 09:01:47

您可以使用值提供程序,它将把查询字符串中的值填充到单个对象中。如果您不打算创建视图模型,这就是您要做的事情。

通过以下方式将 QueryString 转换为 FormCollection:

var GetCollection = new FormCollection( Request.QueryString );

You can you a values provider, and it will populate values from the querystring into a single object. This is what you would do if you're not going to create a View Model.

Transform the QueryString into a FormCollection via:

var GetCollection = new FormCollection( Request.QueryString );
墨小沫ゞ 2024-12-01 09:01:47

您可以创建一个自定义模型绑定器,它在Request.QueryString 集合上工作,而不是常规的FormCollection

例如:

public class MyTestObjectModelBinder : DefaultModelBinder 
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    {
        var qs = controllerContext.HttpContext.Request.QueryString;                  
        return new MyTestObject
        {
           Name = qs["Name"],
           Id = qs["Id"],
           // etc, etc
        };
    }
}

然后相应地设置您的 [HttpGet] 操作:

[HttpGet]
public ActionResult Index([ModelBinder(typeof(MyTestObjectModelBinder))]MyTestObject m) {

}

如果您愿意,您也可以全局注册它,例如在 Application_Start() 上:

ModelBinders.Binders.Add(typeof(MyTestObject), new MyTestObjectModelBinder());

然后您只需要操作上的模型:

[HttpGet]
public ActionResult Index(MyTestObject m) {

}

说了这么多,如果有这么多参数,一定要问这些参数是从哪里来的?很可能是另一页上的表单。

在这种情况下,这应该是一个 [HttpPost] 操作,参数位于表单集合中,然后常规 MVC 模型绑定将为您处理上述代码。

You could create a custom model binder, that works off the Request.QueryString collection, rather than the regular FormCollection.

E.g:

public class MyTestObjectModelBinder : DefaultModelBinder 
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    {
        var qs = controllerContext.HttpContext.Request.QueryString;                  
        return new MyTestObject
        {
           Name = qs["Name"],
           Id = qs["Id"],
           // etc, etc
        };
    }
}

Then setup your [HttpGet] action accordingly:

[HttpGet]
public ActionResult Index([ModelBinder(typeof(MyTestObjectModelBinder))]MyTestObject m) {

}

You could also register it globally if you like, e.g on Application_Start() :

ModelBinders.Binders.Add(typeof(MyTestObject), new MyTestObjectModelBinder());

Then you just need the model on your action:

[HttpGet]
public ActionResult Index(MyTestObject m) {

}

Having said all of this, if you've got this many parameters, one must ask where do these parameters come from? Most likely a form on another page.

In which case, this should be a [HttpPost] action, with the parameters in the form collection, then the regular MVC model binding will take care of the above code for you.

旧情勿念 2024-12-01 09:01:47

是的,ASP.NET MVC 可以自动将集合绑定到操作参数,但是您需要将参数作为 from 值传递,而且,您似乎要在查询字符串中传递许多参数。看看这个 http://weblogs.asp.net/nmarun/archive/2010/03/13/asp-net-mvc-2-model-binding-for-a-collection.aspx

基本上你需要的要做的事情:

1) 创建包含参数的类

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

 //do all the rest
}

2) 创建要传递给视图的模型

public class MyViewModel
{
  IList<MyParam> MyParams {get; set;}
}

3) 在 [HttpGet] 操作中创建集合并将其传递给视图:

[HttpGet]
public virtual ActionResult Index()
{
   MyViewModel model = new MyViewModel();
   model.MyParams = CreateMyParamsCollection();

   return View(model);
}

4)在视图中迭代您的集合

@model MyViewModel

@{int index = 0;}

@foreach (MyParam detail in Model.MyParams)
{
  @Html.TextBox("MyParams[" + index.ToString() + "].Id", detail.Id)
  @Html.TextBox("MyParams[" + index.ToString() + "].Name", detail.Name)

  index++;
} 

5)比在您的 [HttpPost] 操作中,您可以在集合

[HttpPost]
public virtual ActionResult Index(MyViewModel model)

[HttpPost]
public virtual ActionResult Index(IList<MyParam> model)

PS

中捕获您的参数此外,如果您想获取所有表单控制器中的参数你可以简单地像这样:

[HttpPost]    
public virtual ActionResult Index(FormCollection form)

Yes, ASP.NET MVC could automatically bind collections to action params, but you need to pass your params as a from values, moreover, it is looks like to many params you going pass in query string. Have look at this one http://weblogs.asp.net/nmarun/archive/2010/03/13/asp-net-mvc-2-model-binding-for-a-collection.aspx

Basically what you need to do:

1) Create your class which would contain your params

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

 //do all the rest
}

2) Create model which you would pass to your view

public class MyViewModel
{
  IList<MyParam> MyParams {get; set;}
}

3) Create your collection in your [HttpGet] action and pass that to your view:

[HttpGet]
public virtual ActionResult Index()
{
   MyViewModel model = new MyViewModel();
   model.MyParams = CreateMyParamsCollection();

   return View(model);
}

4) Iterate your collection in the view

@model MyViewModel

@{int index = 0;}

@foreach (MyParam detail in Model.MyParams)
{
  @Html.TextBox("MyParams[" + index.ToString() + "].Id", detail.Id)
  @Html.TextBox("MyParams[" + index.ToString() + "].Name", detail.Name)

  index++;
} 

5) Than on your [HttpPost] action you may catch your params in collection

[HttpPost]
public virtual ActionResult Index(MyViewModel model)

or

[HttpPost]
public virtual ActionResult Index(IList<MyParam> model)

P.S

Moreover, if you want to get all your form params in controller you may simple go like that:

[HttpPost]    
public virtual ActionResult Index(FormCollection form)
小苏打饼 2024-12-01 09:01:47

与此相关的是,我一直在寻找一种枚举 QueryString 名称-值集合的方法,这就是我想到的:

        var qry =HttpContext.Request.QueryString;

        if (qry.HasKeys())
        {
            foreach (var key in qry)
            {
                if(key != null)
                    var str= String.Format("Key:{0}, value:{1} ", key, qry.Get(key.ToString()));
            }
        }

此代码将为您提供 QueryString 中的所有名称及其值。

On a related note, I was looking for a way to enumerate through the QueryString name-value collection, and this is what I came up with:

        var qry =HttpContext.Request.QueryString;

        if (qry.HasKeys())
        {
            foreach (var key in qry)
            {
                if(key != null)
                    var str= String.Format("Key:{0}, value:{1} ", key, qry.Get(key.ToString()));
            }
        }

This code will give you all the names and their values in the QueryString.

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