Modify post data with a custom MVC extension?

孤街醉人 提交于 2019-12-23 05:03:02

问题


So I'm looking into writing some custom MVC extensions and the first one I'm attempting to tackle is a FormattedTextBox to handle things such as currency, dates, and times. I have the rendering of it working perfectly, formatting it, working with strong types and everything all golden. However, the problem I'm now running into is cleaning up the formatted stuff when the page posts the data back.

Take for example, a currency format. Let's use USD for these examples. When an object has a property as a decimal, the value would be 79.95. Your edit view would be something like:

<%= Html.FormattedTextBox(model => Model.Person.HourlyWage, "{0:C}") %>

This is all well and good for the GET request, but upon POST, the value is going to be $79.95, which when you assign to that decimal, gets unhappy very quickly and ends up shoving a 0 in there.

So my question is, how do I get code working somewhere to work with that value before the MVC Framework goes and starts shoving it back into my ViewModel? I'd much rather this be done server-side than client-side.

Thanks!!


回答1:


One solution would be to write a custom model binder which will be able to convert bind $79.95 to a decimal field in your model. Another solution is to do it on the client side. In a jQuery form.submit handler you could modify the values of the input fields to be posted.




回答2:


You can use custom Model Binders to shove the posted data into an object.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(
    [ModelBinder(typeof(YourModelBinderAttribute))]YourClass obj)
{
  // your code here

  return View();
}

public class MessageModelBinderAttribute : IModelBinder
{
    #region IModelBinder Members

    public object BindModel(
        ControllerContext controllerContext, 
        ModelBindingContext bindingContext)
    {
        YourClass obj = new YourClass();

        ValueProviderResult result;
        if (bindingContext.ValueProvider.TryGetValue(
            "YourPostedInputName", out result))
        {
            obj.Price = result.AttemptedValue;
        }

        return message;
    }

    #endregion
}


来源:https://stackoverflow.com/questions/2542576/modify-post-data-with-a-custom-mvc-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!