假设我有一个
<form method="post" action"/user/create">
<input type="text" name="FirstName" placeholder="FirstName" />
<button type="submit">Submit</button>
</form>
我想在我的操作方法中访问输入值FirstName。
public IActionResult Create(IFormCollection form)
{
string FirstName = form.Keys["FirstName"];
return View();
}
它给出了一个错误"Cannot apply indexing with [] to an expresion of type ICollection“
我知道我可以迭代并放置一个if语句,但我发现这需要太多的代码。我刚开始学习c#,但在Node.js和Python语言中,获取表单post值非常容易,例如在节点中。
request.body.FirstName;
就是这样。我正在寻找一些类似的东西,没有迭代或创建一个poco类。
谢谢。
发布于 2017-08-18 13:40:01
简单的答案
您可以使用form["FirstName"]
或form.Get("FirstName")
。
edit 你提到过,你不想创建一个poco。但是,如果您有多个参数,请考虑一下:
原创内容:
我更喜欢创建一个类(比如person,它有一个FirstName属性),并使用内置序列化的优点。
如果您的表单参数如下所示:
{
"FirstName": "John",
"LastName": "Doe"
}
那么你的类应该是:
public class Person {
public string FirstName {get;set;}
public string LastName {get;set;}
}
您的Create方法应该如下所示
public IActionResult Create([FromForm]Person p)
{
string FirstName = p.FirstName;
}
它会自动将表单参数解析到Person对象中。
读取表单参数是一种多么干净的方式,不是吗;-)?
发布于 2017-08-17 03:23:46
https://stackoverflow.com/questions/45725952
复制相似问题