简体   繁体   中英

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.

Using the following code I get an error at line ... 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'

It looks like you're trying to do something in 'webforms style', instead of 'MVC style'.

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. The 'webforms' URL would have been something like /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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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