4

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.

But please tell me how I can pick value of skip_api_login , api_key , signed_next in asp.net MVC4 razor .

I want to use those values in controller and views. Please tell me how to pick them.

1 Answer 1

6

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["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. A view in ASP.NET MVC has a single responsibility: use the information from the view model.

Sign up to request clarification or add additional context in comments.

5 Comments

bot what happened if one of them is not available in url . also is i need to register those keys in RouteConfig file
My eyes cried blood a little when I saw that last part :)
@SourabhDevpura, if it is not available, the value will be null. As far as routing is concerned, query strings parameters do not participate in any RouteConfigs. Your route definition patterns should contain only the path portions of your urls and exclude any query string parameters.
@SimonWhitehead why ?
@SourabhDevpura ..because it makes me sad to see MVC not being used the way it should be. I spent all of yesterday cleaning up a View and Controller that a former employee created that relied on FormCollection and manually checking Request.QueryString. It was just awful. Ps: I still +1'd.. because I know Darin only mentioned that because every answer he gives covers all angles.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.