简体   繁体   English

如何在控制器中分配查询字符串?

[英]How to assign a query string in a controller?

Using MVC 3 Asp.Net, I would like to add a default Query String on any method in a controller. 使用MVC 3 Asp.Net,我想在控制器中的任何方法上添加默认查询字符串。

Using the following code I get an error at line ... QueryString.Add(): 使用以下代码,在第QueryString.Add()行出现错误:

Collection is read only.

Any idea how to fix it, or do you know a better way how to append a query string to method of a controller? 知道如何解决它,或者您知道如何将查询字符串追加到控制器方法的更好方法吗? Please post a sample of code thanks. 请发表代码示例感谢。

   public class HomeController : Controller
    {

        protected override void Initialize(RequestContext requestContext)
        {
            // Add the User's ID if is not present in the request
            string user = requestContext.HttpContext.Request.QueryString["UniqueStudentReference"];
            if (user == null)
            {

                string userId = Various.GetGivenNameUser();
                System.Web.HttpContext.Current.Request.QueryString.Add("UniqueStudentReference", userId);
            }

                base.Initialize(requestContext);
        }
...

What about redirecting? 重定向呢?

    protected override void Initialize(RequestContext requestContext)
    {
        // Add the User's ID if is not present in the request
        string user = requestContext.HttpContext.Request.QueryString["UniqueStudentReference"];
        if (user == null)
        {

            string userId = Various.GetGivenNameUser();

            requestContext.HttpContext.Response.RedirectToRoute(new { UniqueStudentReference = userId });
        }

        base.Initialize(requestContext);
    }

This should redirect to the same route just adding a query string parameter 'UniqueStudentReference' 只需添加查询字符串参数“ UniqueStudentReference”,即可重定向到同一路由

It looks like you're trying to do something in 'webforms style', instead of 'MVC style'. 看起来您正在尝试以“ Webforms样式”而不是“ MVC样式”进行操作。

The default template for MVC is set up so that you can specify ID's in the URL, for example /Home/User/1 would give you ID=1. 设置了MVC的默认模板,以便您可以在URL中指定ID,例如/ Home / User / 1将为您提供ID = 1。 The 'webforms' URL would have been something like /users.aspx?id=1. “ webforms” URL可能类似于/users.aspx?id=1。

So my guess is that you just have to create an ActionMethod like 所以我的猜测是,您只需要创建一个像

public ViewResult User(int id)
{
    return View(userRepository.Find(id)); // example where you're using EntityFramework
}

Actual name of the method may be something different offcourse. 该方法的实际名称可能与其他方法有所不同。 But the important thing is that the ID parameter will be set automatically by the MVC framework. 但是重要的是ID参数将由MVC框架自动设置。

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

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