如何将数据从视图传递到控制器
在我的视图中,我有一个表提取各种数据。最初它只显示该用户可操作的行。但是,还有一个显示所有行的选项。到目前为止,为了实现这一目标,我在表格上方有两个超链接,其 href 为“?isRequiredAction=true”和“?isRequiredAction=false”。在控制器中,我有以下内容:
public ActionResult Index(bool? isRequiredAction){
string userId = User.Identity.Name;
bool ira = true;
if (isRequiredAction != null)
{
ira = Convert.ToBoolean(isRequiredAction);
}
...
return View(model);
因此,现在控制器正在从通过单击这些链接创建的查询字符串中获取其参数。我对这种方法不满意,因为我不想用这个查询弄脏 URL。有没有更简单的方法来实现我的要求?如果可能的话,我们希望避免将链接变成表单对象。谢谢。
In my View, I have a table pulling various data in. Initially it only shows the rows actionable by that user. However, there is also an option to show all rows. To achieve that so far, I have two hyperlinks above the table, with hrefs of "?isRequiredAction=true" and "?isRequiredAction=false". In the Controller, I have the following:
public ActionResult Index(bool? isRequiredAction){
string userId = User.Identity.Name;
bool ira = true;
if (isRequiredAction != null)
{
ira = Convert.ToBoolean(isRequiredAction);
}
...
return View(model);
So, right now the Controller is getting its parameter from the querystring created by clicking those links. I'm not satisfied with this approach since I don't want to dirty up the URL with this query. Is there a simpler way of achieving what I'm asking? We would like to avoid turning the links into form objects if possible. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这篇 MSDN 文章应该有所帮助。
从视图到控制器,您可以执行
HttpPost
,也可以将数据作为参数传递。This MSDN article should help.
From view to controller, you can do a
HttpPost
or you can pass the data as parameters.您可以创建两个不同的自定义路由,例如:
之后,您可以使两个路由针对相同的操作,或为每个路由创建不同的操作。您的选择!
You can create two distinct custom routes, for example:
After that, you can make both routes target the same action or create a distinct action for each of these routes. Your choice!
从技术上讲,我不认为有非常合适的解决方案可以满足您的需求,因为您不想创建链接表单对象,也不想“弄脏”URL。我建议您坚持使用第一种方法,因为弄脏 URL 并没有什么问题。通过“弄脏”您的 URL,您可以使链接成为书签。如果您确实关心它,那么您可以有两种选择:
(1) 使用 Ajax。这样你的URL就不会受到影响;但是,您会失去可收藏性。
(2)使用URL重写让你的URL变得“漂亮”。这种方法在本质上相当于“弄脏”URL,但是以一种“漂亮”的方式。
Technically, I don't believe there is very appropiriate solution that fits your need because you don't want to make the link form object, nor "dirtying up" the URL. I suggest you to stick with your first approach because there is nothing wrong with dirtying the URL. By "dirtying" your URL, you can make link bookmarkable. If you are really concerned with it, then you can have two choices:
(1) Use Ajax. This way your URL will be unaffected; however, you lose bookmarkability.
(2) Use URL rewriting to make your URL "pretty". This approach, under the hood, equals to "dirtying up" the URL, but in a "pretty" way.