加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – asp.net mvc提交时的表单集合

发布时间:2020-12-16 04:19:56 所属栏目:asp.Net 来源:网络整理
导读:在asp.net mvc中提交表单的最佳做法是什么?我一直在做这样的代码,但我觉得有更好的方法.建议? [AcceptVerbs(HttpVerbs.Post)] public ActionResult AddNewLink(FormCollection collection_) { string url = collection_["url"].ToString(); string descrip
在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);

解决方法

您可以直接使用参数;参数将自动解析并转换为正确的类型.方法中的参数名称必须与从表单中发布的参数名称匹配.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddNewLink(string url,string description,string tagsString)
{
    string[] tags = tagsString.Replace(" ",');

    linkRepository.AddLink(url,tags);
}

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

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(" ",tags);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读