ASP.NET MVC模型表单名破折号绑定 [英] ASP.NET MVC Model Binding with Dashes in Form Element Names

查看:116
本文介绍了ASP.NET MVC模型表单名破折号绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在网上淘试图找到一种方法,以适应从我的表单元素融入ASP.NET的控制器的默认模型绑定行为破折号MVC 2,3,甚至是4。

I have been scouring the internet trying to find a way to accomodate dashes from my form elements into the default model binding behavior of ASP.NET's Controllers in MVC 2, 3, or even 4.

作为前端开发人员,我preFER破折号在我的CSS在驼峰或下划线。在我的标记,我想做什么就能做的是这样的:

As a front-end developer, I prefer dashes in my CSS over camelCase or underscores. In my markup, what I want to be able to do to is something like this:

<input type="text" name="first-name" class="required" />
<input type="text" name="last-name" class="required" />

在控制器中,我将传递一个C#对象,应该是这样的:

In the controller, I would be passing in a C# object that would look like this:

public class Person
{
      public string FirstName { get; set; }
      public string LastName { get; set; }
      //etc...
}

有没有一些方法来延长控制器类来通过一些正则表达式或其他行为适应这种?我恨,我必须做这样的事情的事实:

Is there some way to extend the Controller class to accommodate this through some regex or other behavior? I hate the fact that I have to do something like this:

<input type="text" name="person.firstname" class="required" />

甚至是这样的:

<input type="text" name="isPersonAttending" class="required" />

思考?

推荐答案

您总是可以创建自己的模型粘合剂。

You could always create your own model binder.

下面是实现粘合剂的支持添加别名性能型号的例子:

Here's an example that implements a binder that supports adding Aliases to model properties:

<一个href=\"http://ole.michelsen.dk/blog/bind-a-model-property-to-a-different-named-query-string-field/\">http://ole.michelsen.dk/blog/bind-a-model-property-to-a-different-named-query-string-field/

和用它做类似:

[ModelBinder(typeof(AliasModelBinder))]
public class Person
{
      [BindAlias("first-name")]
      public string FirstName { get; set; }
      [BindAlias("last-name")]
      public string LastName { get; set; }
      //etc...
}

编辑:
这个实现,因为博客说,是基于安德拉什以下SO问题的答案:
<一href=\"http://stackoverflow.com/questions/4316301/asp-net-mvc-2-bind-a-models-property-to-a-different-named-value#answer-4316327\">Asp.Net MVC 2 - 绑定模型的属性不同的命名值

这篇关于ASP.NET MVC模型表单名破折号绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆