简体   繁体   English

如何在ASP.Net MVC4 Razor中选择查询字符串

[英]How to pick query string in ASP.Net MVC4 Razor

I have a URL like that 我有这样的网址

http://localhost:1243/home/index/?skip_api_login=1&api_key=145044622175352&signed_next=1

Now home is my controller index is my action. 现在home是我的控制器index是我的行动。

But please tell me how I can pick value of skip_api_login , api_key , signed_next in asp.net MVC4 razor . 但请告诉我如何在asp.net MVC4剃须刀中选择skip_api_loginapi_keysigned_next值。

I want to use those values in controller and views. 我想在控制器和视图中使用这些值。 Please tell me how to pick them. 请告诉我如何挑选它们。

You could have your controller action take them as parameters and the model binder will set their values form the query string: 您可以让控制器操作将它们作为参数,模型绑定器将从查询字符串中设置它们的值:

public ActionResult Index(string skip_api_login , string api_key, int signed_next)
{
    ...
}

or event better, write a view model: 或事件更好,写一个视图模型:

public class MyViewModel
{
    public string Skip_api_login { get; set; }
    public string Api_key { get; set; }
    public int Signed_next { get; set; }
}

that your Index action will take as parameter: 您的索引操作将作为参数:

public ActionResult Index(MyViewModel model)
{
    ...
    return View(model);
}

and then your view could be strongly typed to this view model and you will be able to access those values: 然后您的视图可以强烈输入到此视图模型,您将能够访问这些值:

@model MyViewModel
...
@Html.DisplayFor(x => x.Skip_api_login)
@Html.DisplayFor(x => x.Api_key)
@Html.DisplayFor(x => x.Signed_next)

Of course you could always access query string parameters from the Request object: 当然,您始终可以从Request对象访问查询字符串参数:

@Request["skip_api_login"]

But you probably don't want to be doing such things in your view. 但是你可能不希望在你看来做这些事情。 Remember that a view is supposed to work only with the values that the controller action has provided it under the form of a view model. 请记住,视图应该仅适用于控制器操作以视图模型的形式提供的值。 A view is not supposed to be fetching values from request, sessions, viewdatas, viewbags, databases, and whatever comes to your mind. 视图不应该从请求,会话,viewdatas,viewbags,数据库以及您想到的任何内容中获取值。 A view in ASP.NET MVC has a single responsibility: use the information from the view model. ASP.NET MVC中的视图只有一个责任:使用视图模型中的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM