如何改变表单值后张贴在ASP.净MVC

本文关键字:张贴 ASP MVC 表单 何改变 改变 | 更新日期: 2023-09-27 18:05:59

我想在传递给控制器的动作之前改变表单值。但它抛出了Collection is read-only.

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

如何改变表单值后张贴在ASP.净MVC

如果我理解正确的话,您想要修改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;
  }
}

在全球。当你注册绑定器

protected void Application_Start()
{
  AreaRegistration.RegisterAllAreas();
  RegisterGlobalFilters(GlobalFilters.Filters);
  RegisterRoutes(RouteTable.Routes);
  ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
}

在我看来,这是一个更好的方法,你不必为每个动作都添加一个属性