【问题标题】:Sending Advanced Parameters to ASP.Net MVC向 ASP.Net MVC 发送高级参数
【发布时间】:2017-08-25 16:30:37
【问题描述】:

我不知道如何正确表达这个问题,但基本上我有一个 ASP.Net 应用程序。我从我的角度向控制器发送以下请求:

http://localhost:59112/Contacts/IndexJson?current=1&rowCount=50&sort%5BLastName%5D=desc&searchPhrase=&_=1490960196673

我为此请求数据的结构编写了两个不能 100% 工作的类,如下所示:

public class RequestData
{
    public int current { get; set; }
    public int rowCount { get; set; }
    public string searchPhrase { get; set; }
    public IEnumerable<SortData> sortItems { get; set; }
}
public class SortData
{
    public string Field { get; set; } // FIeld Name
    public string Type { get; set; } // ASC or DESC
}

然后在我的控制器中,我有以下内容:

public JsonResult IndexJson(RequestData model)
{
    /* Irrelevant code */
}

除了sortItems 返回 null 之外,模型可以正常工作并正确填充所有内容。如何获得在我的班级中定义的 sortItems FieldType

由于来自RequestData 的参数是sort[Field]=Type

编辑

我将我的 RequestData 课程更改为:

public class RequestData
{
    public int current { get; set; }
    public int rowCount { get; set; }
    public Dictionary<string, string> sort { get; set; }
    public string searchPhrase { get; set; }
    public Guid id { get; set; }
}

现在modelsort 保存为{[Field, Type]}(数据示例)。

如果这是一个好的做法,我如何访问FieldType

【问题讨论】:

  • 我尝试编辑您的问题,因为其中一个课程没有格式。添加了 4 个空格,但最少编辑为 6 个!
  • 抱歉,刚刚批准了修改。感谢您指出。

标签: c# asp.net-mvc request url-parameters


【解决方案1】:

您可以通过多种不同的方式实现这一目标;在每种情况下,您的问题只是没有遵循该数据类型的模型绑定器约定。

首先,如果您打算回帖,IEnumerable 已发布。它不是可索引类型,因此模型绑定器将永远无法绑定到它。但是,使用 List 之类的东西就可以了。然后,您的参数名称只需采用以下格式:ListProperty[N].Property,其中N 是索引。因此,对于您的情况,您可以使用 sortItems[0].Field=LastName&amp;sortItems[0].Type=desc,它会很好地绑定到您的模型。

对于使用字典,您的姓名应采用DictionaryProperty[N].KeyDictionaryProperty[N].Value 的格式,其中N 是索引。在您的场景中,这看起来像 sort[0].Key=LastName&amp;sort[0].Value=desc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 2015-11-21
    • 2010-12-05
    • 2015-10-23
    • 1970-01-01
    相关资源
    最近更新 更多