asp.net mvc的形式提交收集时 [英] asp.net mvc Forms Collection when submitting

查看:113
本文介绍了asp.net mvc的形式提交收集时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是在asp.net mvc的提交表单的最佳实践。我一直在做code这样的低于但我有一种感觉,有一种更好的方式。建议?

 的[AcceptVerbs(HttpVerbs.Post)
    公众的ActionResult AddNewLink(的FormCollection collection_)
    {
        字符串的URL =集_ [网址]的ToString()。
        字符串描述=集_ [说明]的ToString()。
        。字符串tagsString =集_ [标签]的ToString();
        。字符串[] =标签tagsString.Replace(,),斯普利特('');        linkRepository.AddLink(URL,描述,标签);


解决方案

您可以直接使用参数;这些参数将自动获得解析并铸造到正确的类型。在方法的参数名称必须是从您的形式张贴的参数名称相匹配。

 的[AcceptVerbs(HttpVerbs.Post)
公众的ActionResult AddNewLink(URL字符串,字符串描述,字符串tagsString)
{
    。字符串[] =标签tagsString.Replace(,),斯普利特('');    linkRepository.AddLink(URL,描述,标签);
}

这一般适用于更复杂的对象,以及,只要它的属性进行设置,只要你的表单钥匙格式objectName.PropertyName。如果你需要什么更高级的,你应该看看模型粘合剂

 公共类为MyObject
{
    公众诠释标识{搞定;组;}
    公共字符串文本{搞定;组;}
}的[AcceptVerbs(HttpVerbs.Post)
公众的ActionResult AddNewLink(为MyObject OBJ)
{
    字符串[] =标签obj.Text.Replace(,),斯普利特('')。    linkRepository.AddLink(URL,描述,标签);
}

what is the best practice for submitting forms in asp.net mvc. I have been doing code like this below but i have a feeling there is a better way. suggestions?

    [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);

You can use the parameters directly; the parameters will automatically get parsed and casted to its correct type. The parameter names in the method must match the parameter names that are posted from your form.

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

    linkRepository.AddLink(url, description, tags);
}

This generally works on more complex objects as well, as long as its properties can be set, and as long as your form keys are in the format objectName.PropertyName. If you need anything more advanced, you should look into 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(" ","").Split(',');

    linkRepository.AddLink(url, description, tags);
}

这篇关于asp.net mvc的形式提交收集时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆