【问题标题】:How to pass query parameter and class attribute to Html.BeginForm in MVC3?如何在 MVC3 中将查询参数和类属性传递给 Html.BeginForm?
【发布时间】:2012-04-17 00:46:02
【问题描述】:

我对 MVC3 中的 Html 助手有点困惑。

我之前创建表单时使用了这种语法:

@using (Html.BeginForm("action", "controller", FormMethod.Post, new { @class = "auth-form" })) { ... }

这给了我

<form action="/controller/action" class="auth-form" method="post">...</form>

好吧,那正是我需要的。

现在我需要将 ReturnUrl 参数传递给表单,所以我可以这样做:

@using (Html.BeginForm("action", "controller", new { ReturnUrl="myurl" } )) { ... }

这会给我

<form action="/controller/action?ReturnUrl=myurl" method="post"></form>

但是我仍然需要将 css 类和 id 传递给这个表单,我找不到同时传递 ReturnUrl 参数的方法。

如果我添加FormMethod.Post,它会将我的所有参数作为属性添加到表单标记中,如果没有FormMethod.Post,它会将它们添加为查询字符串参数。

我该怎么做?

谢谢。

【问题讨论】:

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


    【解决方案1】:

    你可以使用:

    @using (Html.BeginForm("action", "controller", new { ReturnUrl="myurl" }, FormMethod.Post, new { @class = "auth-form" })) { ... }
    

    这将给出:

    <form action="/controller/action?ReturnUrl=myurl" class="auth-form" method="post">
       ...
    </form>
    

    【讨论】:

    • 谢谢 pjumble,这正是我所需要的。没有尝试将 ReturnUrl 放在 FormMethod.Post 之前。那里正在发生一些魔法,没有人的帮助很难弄清楚。
    【解决方案2】:

    1-更难的方式:在外部定义routeValues,然后使用变量

    @{
        var routeValues = new RouteValueDictionary();
        routeValues.Add("UserId", "5");
        // you can read the current QueryString from URL with equest.QueryString["userId"]
    }
    @using (Html.BeginForm("Login", "Account", routeValues))
    {
        @Html.TextBox("Name");
        @Html.Password("Password");
        <input type="submit" value="Sign In">
    }
    // Produces the following form element
    // <form action="/Account/Login?UserId=5" action="post">
    

    2- 更简单的内联方式:在 Razor 内部使用 Route 值

    @using (Html.BeginForm("Login", "Account", new { UserId = "5" }, FormMethod.Post, new { Id = "Form1" }))
    {
        @Html.TextBox("Name");
        @Html.Password("Password");
        <input type="submit" value="Sign In">
    }
    // Produces the following form element
    // <form Id="Form1" action="/Account/Login?UserId=5" action="post">
    

    请注意,如果您想添加帖子 (FormMethod.Post) 或明确获取它在 routeValues 参数之后

    official source with good examples

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      • 1970-01-01
      • 2018-09-30
      • 2017-05-28
      • 2019-03-21
      • 1970-01-01
      • 2011-08-15
      相关资源
      最近更新 更多