将Html.BeginForm与querystring一起使用 [英] Using Html.BeginForm with querystring
问题描述
我的网址看起来像这样:
My url looks like this:
customer/login?ReturnUrl=home
在登录视图中,我使用了这种模式的代码,效果很好.
In the login view, I have used this pattern of code which works fine.
@using(Html.BeginForm())
{
...
}
这神奇地生成了以下html
This magically generates following html
<form action="customer/login?ReturnUrl=home" method="post">
但是现在,我需要在表单中添加一个属性(例如,data-id="something"
).我怎样才能做到这一点?如果我没有任何查询字符串,我知道我可以做这样的事情:
But now, I need to add an attribute (e.g., data-id="something"
) in the form. How can I do that? If I don't have any query string, I know I can do something like this:
@using(Html.BeginForm(action, controller, FormMethod.Post,
new { data_id="something" }))
但是不知道如何添加应该在html中的querystring:
But don't know how to add querystring which should be in html:
<form action="customer/login?ReturnUrl=home" method="post" data-id="something">
我考虑过直接使用<form>
,但是不知道如何指定可变的querystring.而且我不知道如何使用Html.BeginForm
实现它.任何提示将不胜感激.
I thought about using <form>
directly but don't know how to specify querystring which is variable. And I have no idea how to achieve it with Html.BeginForm
. Any tip would be appreciated.
解决方案:
目前,我将<form>
与以下提示结合使用如何在View中获取当前的URL值.产生的视图看起来像
For now, I used <form>
with following hint How to get current url value in View. The resulting view looks like
<form action="@Request.Url.PathAndQuery" data-id="something" method="POST">
但是,对此有一个BeginForm
的重载方法会很好.
But it would be nice to have an overloaded method of BeginForm
for this.
推荐答案
我想这并不能直接回答问题,但是为什么不只使用普通的旧表单标签呢?
I guess this doesn't directly answer the question, but why not just use a plain old form tag?
<form action='customer/login?ReturnUrl=@Request.QueryString["ReturnUrl"]' method="post" data-id="something">
或者,您可以创建一个自定义的HtmlHelperExtension来呈现带有路径和查询字符串的表单.在此HtmlHelperExtension中,您可以遍历查询字符串值并填充routeValueDictionary,然后将其传递给Html.BeginForm构造函数.
Alternatively, you can create a custom HtmlHelperExtension that renders a form with path and querystring. In this HtmlHelperExtension you can iterate through your querystring values and populate the routeValueDictionary which you then pass to a Html.BeginForm constructor.
如果您不想要这样的可扩展性,则可以使用Html.BeginForm的重载构造函数,方法是:
@Html.BeginForm("login", "customer", new {ReturnUrl = @Request.QueryString["ReturnUrl"]},FormMethod.Post, new {data-id="something"});
If you don't want something so extensible you can just use the overloaded constructor of Html.BeginForm using
@Html.BeginForm("login", "customer", new {ReturnUrl = @Request.QueryString["ReturnUrl"]},FormMethod.Post, new {data-id="something"});
这篇关于将Html.BeginForm与querystring一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!