【问题标题】:Adding a class to an Ajax.BeginForm Call in Razor View Model将类添加到 Razor 视图模型中的 Ajax.BeginForm 调用
【发布时间】:2012-02-08 23:24:11
【问题描述】:

我有如下代码

@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "update_panel", Url = "/Part/SearchPart" }))
        {
            <input type="text" placeholder="Search Parts"/>
            <input type="submit" value="Search"/>
        }

它输出以下 HTML

<form action="/Part" data-ajax="true" data-ajax-mode="replace" data-ajax-update="#update_panel" data-ajax-url="/Part/SearchPart" id="form0" method="post">                        
    <input type="text" placeholder="Search Parts"/>
        <input type="submit" value="Search"/>
</form>

并且我希望输出的 HTML 具有 ,form> 标记以具有 class="pull-right"。我怎样才能做到这一点?

【问题讨论】:

    标签: asp.net-mvc-3 html razor


    【解决方案1】:

    你必须把你的行动和控制从你的表格中引用。

    示例如下:

    @using (Ajax.BeginForm("LogOn","Account", new AjaxOptions { UpdateTargetId = "update_panel", Url = "/Part/SearchPart" }, new { @class ="pull-right"}))
    {
        <input type="text" placeholder="Search Parts"/>
        <input type="submit" value="Search"/>
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用one of the overloads 来指定html 属性::

      @using (Ajax.BeginForm(null, null, new AjaxOptions { UpdateTargetId = "update_panel", Url = "/Part/SearchPart" }, new { @class = "pull-right" }))
      {
          <input type="text" placeholder="Search Parts"/>
          <input type="submit" value="Search"/>
      }
      

      此外,我强烈建议您依赖表单的 url 而不是在 AjaxOptions 中硬编码它,因为当您将应用程序部署到虚拟目录中时,您的硬编码 /Part/SearchPart url 可能不起作用。更不用说您是否更改了 Global.asax 中的路线模式。所以:

      @using (Ajax.BeginForm("SearchPart", "Part", null, new AjaxOptions { UpdateTargetId = "update_panel" }, new { @class = "pull-right" }))
      {
          <input type="text" placeholder="Search Parts"/>
          <input type="submit" value="Search"/>
      }
      

      【讨论】:

      • 效果很好。感谢您的帮助,您关于不对网址进行硬编码的观点也得到了很好的理解。
      猜你喜欢
      • 2019-09-25
      • 2019-10-16
      • 2019-06-02
      • 2016-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-13
      • 1970-01-01
      相关资源
      最近更新 更多