关于asp.net mvc模型绑定及其参数
这是视图模型的
public class ArticleViewModel
{
public string ID { get; set; }
public string Title{ get; set; }
public string Body { get; set; }
public List<BETag> TagsList { get; set; }
}
public class BETag
{
public string ID { get; set; }
public string Name { get; set; }
}
一个操作
[HttpPost, AuthorizeEx]
public ActionResult AddArticle(ArticleViewModel articleViewModel)
{
//articleViewModel.Tags.Count == 0
//Request.Form["TagsList"] == "tag1, tag2..."
}
和 AddArticle.cshtml
的一部分
@Html.TextAreaFor(m => m.TagsList )
我的问题是为什么 articleViewModel.Tags.Count
等于 0
,但是 Request.Form["TagsList"]
是否等于"tag1, tag2..."
?如何正确绑定ArticleViewModel
?
Here is view models
public class ArticleViewModel
{
public string ID { get; set; }
public string Title{ get; set; }
public string Body { get; set; }
public List<BETag> TagsList { get; set; }
}
public class BETag
{
public string ID { get; set; }
public string Name { get; set; }
}
An action
[HttpPost, AuthorizeEx]
public ActionResult AddArticle(ArticleViewModel articleViewModel)
{
//articleViewModel.Tags.Count == 0
//Request.Form["TagsList"] == "tag1, tag2..."
}
and a part of AddArticle.cshtml
@Html.TextAreaFor(m => m.TagsList )
My question is why articleViewModel.Tags.Count
is equal 0
, butRequest.Form["TagsList"]
is equal "tag1, tag2..."
? How to bind ArticleViewModel
properly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
列表在 MVC 中不是这样工作的。您需要使用 EditorFor(m => m.TagsList) 之类的东西,然后需要创建一个 BETag EditorTemplate。但这只是问题的一部分,而且对你来说也确实不起作用。
您真正想要的只是一个简单的字符串,它接受您的标签列表,例如
然后,在您的控制器中,您解析该字符串并提取所有标签,然后将它们添加到 TagsList 中。
MVC 适用于单个项目,而不适用于复杂类型。在某些情况下,有一些内置处理可以分解复杂类型,并自动迭代集合,但这些在您的情况下不起作用,因为您想要编辑单个字段中的所有项目。因此,您唯一的选择是解析 post 方法中的字段并将数据放在您想要的位置。
Lists don't work that way in MVC. You need to use something like EditorFor(m => m.TagsList) and then you need to create a BETag EditorTemplate. But that's only part of the problem, and really won't work for you either.
What you really want is just a simple string that takes your list of tags, such as
Then, in your controller, you parse the string and extract all your tags, then add them to the TagsList.
MVC works with single items, not complex types. There is some built-in processing to breakdown complex types in some cases, and to automatically iterate over collections, but those don't work in your case because you want to edit all the items in a single field. So your only option is to parse the field in the post method and put the data where you want it.