2011-08-19 68 views
2

我想在將其傳遞給控制器​​的操作之前更改表單值。但它拋出Collection is read-only.如何在ASP.NET MVC中發佈後更改表單值?

public class PersonController : Controller 
{ 
    public ActionResult Add() 
    { 
     return View(); 
    } 

    [HttpPost] 
    [PersianDateConvertor("birthday")] 
    public ActionResult Add(FormCollection collection) 
    { 
     string firstName = collection["firstName"]; 
     string lastName = collection["lastName"]; 
     string birthday = collection["birthday"]; 

     return View(); 
    } 
} 
public class PersianDateConvertorAttribute : ActionFilterAttribute 
{ 
    string[] fields; 
    public PersianDateConvertorAttribute(params string[] persianDateFieldNames) 
    { 
     if (persianDateFieldNames == null) 
      fields = new string[] { }; 
     else 
      fields = persianDateFieldNames; 
    } 

    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     foreach (var field in fields) 
     { 
      string value = filterContext.HttpContext.Request.Form[field]; 
      filterContext.HttpContext.Request.Form.Remove(field); //throws Collection is read-only 
      filterContext.HttpContext.Request.Form.Add(field, ConvertToGregorian(value)); 
      // or filterContext.HttpContext.Request.Form[field] = ConvertToGregorian(value); 
     } 

     base.OnActionExecuting(filterContext); 
    } 
} 
+0

由於某些原因,我不想轉換d ata我的行動 – Jalal

+0

看看這些SO問題:http://stackoverflow.com/questions/323265/c-can-i-modify-request-forms-variables和http://stackoverflow.com/questions/5561207 /請求形式的信息收集是隻-只讀-時,試圖對設置文本框內容 – Baz1nga

回答

4

如果我理解正確的話,你要結合過程中修改DateTime的行爲。我將使用ModelBinder來更改日期字符串的格式,而不是使用屬性。

我做了一個問題,類似的東西,而從多元文化轉換十進制值:(代碼是從博客文章拍攝,這不是我的,但我不記得源對不起。)

using System; 
using System.Globalization; 
using System.Web.Mvc; 

public class DecimalModelBinder : IModelBinder 
{ 
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
    ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); 
    ModelState modelState = new ModelState { Value = valueResult }; 
    object actualValue = null; 
    try 
    { 
     actualValue = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture); 
    } 
    catch (FormatException e) 
    { 
     modelState.Errors.Add(e); 
    } 
    bindingContext.ModelState.Add(bindingContext.ModelName, modelState); 
    return actualValue; 
    } 
} 

在Global.asax中註冊該粘結劑

protected void Application_Start() 
{ 
    AreaRegistration.RegisterAllAreas(); 
    RegisterGlobalFilters(GlobalFilters.Filters); 
    RegisterRoutes(RouteTable.Routes); 

    ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder()); 

} 

伊莫這是一個更好的方法,你不必把一個屬性,每一個動作

相關問題