使用自定义 MVC 扩展修改发布数据?
-
23-09-2019 - |
题
因此,我正在考虑编写一些自定义 MVC 扩展,我尝试解决的第一个扩展是 FormattedTextBox 来处理货币、日期和时间等内容。我让它的渲染工作完美,格式化它,使用强类型,一切都是金色的。然而,我现在遇到的问题是当页面发回数据时清理格式化的内容。
以货币格式为例。让我们使用美元作为这些示例。当对象具有小数属性时,该值将为 79.95
. 。您的编辑视图将类似于:
<%= Html.FormattedTextBox(model => Model.Person.HourlyWage, "{0:C}") %>
这对于 GET 请求来说一切都很好,但是在 POST 上,该值将是 $79.95
, ,当你分配给那个小数时,它很快就会不高兴并最终推挤一个 0
在那里。
所以我的问题是,在 MVC 框架开始将其推回到我的 ViewModel 之前,如何让代码在某个地方使用该值?我更愿意在服务器端而不是客户端完成此操作。
谢谢!!
解决方案
一个解决办法是写一个定制模型绑定这将能够绑定$79.95
转换为十进制场模型。另一种解决方案是做在客户端。在一个jQuery form.submit
处理程序,你可以修改要过帐的输入字段的值。
其他提示
您可以使用 定制模型活页夹 将发布的数据推送到对象中。
[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
}
不隶属于 StackOverflow