2009-09-07 10 views
7

を提出します。私は以下のようなコードを行ってきましたが、もっと良い方法があると感じています。提案?asp.net MVC Formsコレクションの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); 

答えて

10

パラメータは直接使用できます。パラメーターは自動的に解析され、正しいタイプにキャストされます。メソッドのパラメータ名は、フォームから送信されたパラメータ名と一致する必要があります。

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

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

は、この一般的にその性質がある限り、フォームのキーはフォーマットobjectName.PropertyNameであるように設定することができ、限り、同様に、より複雑なオブジェクト上で動作します。より高度なものが必要な場合は、model bindersを参照する必要があります。

3

私の意見では、モデルバインダーはよりクリーンです。あなたはFormCollectionから望ましいモデルと同様に、検証にご入力を包む、基本的にOdeToCode.com

でより多くを学ぶことができます。コントローラ

public ActionResult AddNewLink(Link link) 

public class LinkModelBinder : IModelBinder 
{ 
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     var link = new Link(); 
     link.Url = GetValue<string>(bindingContext, "url"); 
     // ... and so on for all properties 

     if (String.IsNullOrEmpty(url.Name)) 
     { 
      bindingContext.ModelState.AddModelError("Url", "..."); 
     } 

     return link; 
    } 

    private T GetValue<T>(ModelBindingContext bindingContext, string key) 
    { 
     ValueProviderResult valueResult; 
     bindingContext.ValueProvider.TryGetValue(key, out valueResult);    
     return (T)valueResult.ConvertTo(typeof(T)); 
    } 
} 

関連する問題