user2224493
user2224493

Reputation: 269

Request values from query string

How could i extract House, Car, and Work value from this query string?

http://'mysite'/Result/Environments?House=1&Car=0&Work=1

Then assign values in LINQ statement below.

Action Method in Controller

public ActionResult Environments()
{
    //int totalSmokers = repository.Results.Where(x=>x.House = 
    return View();
}

Upvotes: 2

Views: 353

Answers (4)

Mathew Thompson
Mathew Thompson

Reputation: 56429

You should have your ActionResult take them as parameters, like so (I'm assuming bool, if they're int, change them to int).

public ActionResult Environments(bool House, bool Car, bool Work)

Then you can use them in your LINQ statement, something like:

int totalSmokers = repository.Results
    .Where(x => x.House == House && x.Car == Car && x.Work == Work)
    .Count();


Even cleaner though, you could create a model (and return this in your view like you asked in comments), something like:

public class SmokersModel
{
    public bool House { get; set; }
    public bool Car { get; set; }
    public bool Work { get; set; }
    public int TotalSmokers { get; set; }
}

Then that tidies up your action method, you can do:

public ActionResult Environment(SmokersModel Model)
{
    Model.TotalSmokers = repository.Results
        .Where(x => x.House == Model.House && x.Car == Model.Car && x.Work == Model.Work)
        .Count();

    return View(Model);
}

Then change your view's model type to be SmokersModel:

@model SmokersModel

Upvotes: 2

yoozer8
yoozer8

Reputation: 7489

You can access these through Request.QueryString. There a couple ways to do this. The simplest is probably Request.QueryString["House"], but keep in mind this will be a string. QueryString also has an AllKeys collection, so you can check that to see which values were actually provided.

Upvotes: 0

Obama
Obama

Reputation: 2612

The following example writes the query ?House=1 to the console.

Uri baseUri = new Uri ("http://mysite.com/");
Uri myUri = new Uri (baseUri, "/Result/Environments?House=1&Car=0&Work=1");

Console.WriteLine(myUri.Query);

Hope this Helps!

Upvotes: 1

PSL
PSL

Reputation: 123739

You can add parameters to your Action to retrieve the values passed in the query string.

public ActionResult Environments(int House, int Car, int Work)
      {
        //int totalSmokers = repository.Results.Where(x=>x.House == 
        return View();
      }

You can also get it using Request["House"], Request["Car"] or Request["Work"] inside your function.

Upvotes: 1

Related Questions