我有MVC应用程序返回ResultObjekt后处理FormulaData对象.这是通过HTTP-Post调用的rest API
[HttpPost]
[ActionName("GetResult")]
public ResultObjekt GetResult([FromBody]FormularData values)
{
}
Run Code Online (Sandbox Code Playgroud)
问题:有没有办法从valuesa Dictionary<string, string>或a中读取所有属性IEnumerable<KeyValuePair<string, string>>?
例如
public class FormularData
{
public string Item1 { get; set; }
public string Item2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
应该导致a Dictionary<string,string>()或a IEnumerable<KeyValuePair<string, string>>
有价值的 { {"Item1","Value1"}, {"Item2","Value2"}}
我以前的解决方案与之相关Querystring,HttpGet而不是HttpPost因为我改变了,Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value)所以不再适用.
这是我目前的 - 不是那么漂亮的解决方案:
[HttpPost]
[ActionName("GetResult")]
public ResultObjekt GetResult([FromBody]FormularData values)
{
List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
if (!string.IsNullOrEmpty(values.Item1))
{
list.Add(new KeyValuePair<string, string>("Item1", values.Item1));
}
if (!string.IsNullOrEmpty(values.Item2))
{
list.Add(new KeyValuePair<string, string>("Item2", values.Item2));
}
IEnumerable<KeyValuePair<string, string>> result = list.AsEnumerable();
}
Run Code Online (Sandbox Code Playgroud)
正如评论中许多人已经提到的那样,理想情况下应该使用可以保存表单中的值的模型.根据我的观点,这也是最干净的方式,因为我觉得它更有条理.
如果您需要同时访问这两个,请尽可能尝试重构/重构代码.在我看来,为什么在已经绑定到我们的模型时尝试访问原始表单数据,考虑到表单数据是模型数据的子集.
如果无法进行重构/重组,并且您需要同时访问这两者,那么有几种方法可以做到这一点.
选项1:使用FormCollection:
[HttpPost]
public ResultObjekt GetResult(FormCollection formCol, FormularData model)
{
//Note that here both FormCollection and FormularData are used.
//To get values from FormCollection use something like below:
var item1 = formCol.Get("Item1");
}
Run Code Online (Sandbox Code Playgroud)选项2:使用Request.Form:
[HttpPost]
public ResultObjekt GetResult(FormularData model)
{
//To get values from Form use something like below:
var formData = Request.Form;
var item1 = formData.Get("Item1");
}
Run Code Online (Sandbox Code Playgroud)希望这可以帮助.
更新:正如Lali所指出的,无论你使用FormCollectionor Request.Form,你都可以将其转换为字典:( formData.AllKeys.ToDictionary(k => k, v => formData[v])未经测试),因为两者都是类型NameValueCollection
| 归档时间: |
|
| 查看次数: |
1528 次 |
| 最近记录: |