在MVC HtmlHelpers中从ViewData扩展对象

时间:2011-09-20 20:35:46

标签: c# .net asp.net-mvc-3

我正在使用MVC Ajax Helpers构建一个ajax表单:http://msdn.microsoft.com/en-us/library/dd505013.aspx

代码类似于:

Ajax.BeginForm("ActionName", "ControllerName",
    new {
            SomeProperty = (ViewData["SomeObject"] as SomeClass).SomeProperty,
            AnotherProperty = (ViewData["SomeObject"] as SomeClass).AnotherProperty,
            AllTheProperties = (ViewData["SomeObject"] as SomeClass).AllTheProperties,
            otherProperty= ViewData["otherObject"]
        },
  new AjaxOptions {},
  new {id = "anHtmlId"} );

ViewData["SomeObject"]中还有更多属性。

我想将ViewData["otherObject"]添加到routeData对象中,只需使用尽可能少的行,并且不希望单独列出someObject的所有属性,以便我可以向其添加属性无需在视图中重新访问此代码。

基本上“合并”这些对象以传递,因为routeData参数很有用。


更新:一个想法:

Ajax.BeginForm("ActionName", "ControllerName",
    ViewData["SomeObject"].addThePropertiesOf(ViewData["otherObject"]),
  new AjaxOptions {},
  new {id = "anHtmlId"} );

addThePropertiesOf()返回新合并对象的位置。我不想使用昂贵的反射,否则这似乎不符合要求。

1 个答案:

答案 0 :(得分:4)

向HTML发送一些无法由用户修改的值有什​​么意义,因为它们不是表单的一部分作为输入元素只是为了在回发时将它们重新发送为查询字符串参数?没有意义。这完全是浪费带宽。对我来说,发布此表单时需要发送到服务器的是一些唯一标识符(当然还有用户可以修改的所有表单字段):

Ajax.BeginForm(
    "ActionName", 
    "ControllerName", 
    new { id = (ViewData["SomeObject"] as SomeClass).Id }, 
    new AjaxOptions { }, 
    new { id = "anHtmlId"} 
)
{
    ... some input fields that the user can modify and
        that will automatically be sent to the server when
        the form is submitted
}

当然,对于所有可以修改的值,您将拥有相应的输入字段,其值显然会自动发布到服务器。

最后,在服务器上使用此唯一标识符,以便在呈现表单时从GET操作中的任何位置重新获取原始值。你从某个地方取出它们,对,否则你将无法将它们存储在ViewData中。

请摆脱那些ViewData/ViewBag,定义视图模型并使用强类型视图。我开始对那些永远不会在任何ASP.NET MVC应用程序中使用的弱类型构造表现出一些真正的过敏。

相关问题