2013-03-29 30 views
0

我在我的視圖一個文本框具有以下值:地圖字符串作爲INT-陣列到控制器

「1,3,5,8」 或

「1; 3; 5; 8」 。

是否有可能將這些值作爲int數組映射到控制器方法?

[HttpPost] 
public ActionResult AddUsers(int[] values) 
{ 
    ... 
} 
+0

你是什麼意思?我使用asp.net MVC 3的標準路由設置。 – mosquito87

+0

不,對不起,這是一個HTTP帖子。 – mosquito87

+0

你試圖將數組傳遞給Action方法參數嗎? – 2013-03-29 13:31:04

回答

0

您可以創建自定義模型粘合劑。添加一類,說ArrayIntModelBinder和實施IModelBinder接口:

public class ArrayIntModelBinder : IModelBinder 
{ 
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     if (controllerContext == null) 
      throw new ArgumentNullException("controllerContext"); 
     if (bindingContext == null) 
      throw new ArgumentNullException("bindingContext"); 

     string values = bindingContext.ValueProvider.GetValue("values").AttemptedValue; 
     return Array.ConvertAll(values.Split(new[] { ',', ';' }), int.Parse); 
    } 
} 

在視圖中你有你的文本框:

@using (Html.BeginForm()) 
{ 
    <input type="text" name="values"/> 
    <input type="submit" value="submit"/> 
} 

和新的模型綁定應用到你的行動

[HttpPost] 
public ActionResult AddUsers([ModelBinder(typeof(ArrayIntModelBinder))]int[] values) 
{ 
    ... 
} 

或者您可以在Application_Start註冊爲全球。

當然這個版本的模型聯編程序非常簡單,只是爲了給您提供一個想法。至少必須提供輸入字符串的一些驗證。希望這可以幫助。

相關問題