提交时asp.net mvc Forms Collection

leo*_*ora 7 asp.net-mvc

在asp.net mvc中提交表单的最佳做法是什么?我一直在做这样的代码,但我觉得有更好的方法.建议?

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult AddNewLink(FormCollection collection_)
    {
        string url = collection_["url"].ToString();
        string description = collection_["description"].ToString();
        string tagsString = collection_["tags"].ToString();
        string[] tags = tagsString.Replace(" ","").Split(',');

        linkRepository.AddLink(url, description, tags);
Run Code Online (Sandbox Code Playgroud)

Bla*_*son 10

您可以直接使用参数; 参数将自动解析并转换为正确的类型.方法中的参数名称必须与从表单中发布的参数名称匹配.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddNewLink(string url, string description, string tagsString)
{
    string[] tags = tagsString.Replace(" ","").Split(',');

    linkRepository.AddLink(url, description, tags);
}  
Run Code Online (Sandbox Code Playgroud)

这通常适用于更复杂的对象,只要其属性可以设置,并且只要表单键的格式为objectName.PropertyName即可.如果您需要更高级的东西,您应该查看模型粘合剂.

public class MyObject
{
    public int Id {get; set;}
    public string Text {get; set;}
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddNewLink(MyObject obj)
{
    string[] tags = obj.Text.Replace(" ","").Split(',');

    linkRepository.AddLink(url, description, tags);
}
Run Code Online (Sandbox Code Playgroud)