简体   繁体   中英

ASP.NET MVC Catching and Using Parameter In The View

Here is the ActionLink in the index view.

@Html.ActionLink("€ 50-100", "Filter", new { number1 = 50, number2 = 100 }, null)

Here is the filter method in the controller for catching 2 parameters

[HttpGet]
        public ActionResult Filter(int number1, int number2)
        {          
            var result = db.Gifts.Where(c => c.Price > number1 && c.Price <= number2).ToList();
            return View(result);
        }

All works fine, but i want to use the parameter in the filter view forexample;

<h3> Choose a gift from the list of € number1 - number2 </h3>

How can i do that?

New ViewModel that incorporates the filter params and the resultset:

public class MyViewModel
{
    public int Number1 { get; set; }
    public int Number2 { get; set; }
    public List<Gifts> GiftList { get; set; }
}

Updated action method. You assign the model properties here and pass the model to the View:

public ActionResult Filter(int number1, int number2)
{    
    var model = new MyViewModel
    {
       Number1 = number1,
       Number2 = number2,
       GiftList = db.Gifts.Where(c => c.Price > number1 && c.Price <= number2).ToList()
    }      

     return View(model);
}

Updated View. You need to change the model declaration at the top to use the new model:

@model MyViewModel
<h3> Choose a gift from the list of € @Model.Number1 - @Model.Number2 </h3>

You would iterate over your Gifts result set like this:

@foreach(var item in Model.GiftList)
{
...

Based on your code it looks like you're trying to pass some values form the controller to the view.

You could do this using the ViewBag: Controller:

public ActionResult Filter(int number1, int number2)
{          
    var result = db.Gifts.Where(c => c.Price > number1 && c.Price <= number2).ToList();
    ViewBag.N1 = 50;
    ViewBag.N2 = 100;

    return View();
}

View:
@Html.ActionLink("€ 50-100", "Filter", new { number1 = @ViewBag.N1, number2 = @ViewBag.N2 }, null)

Choose a gift from the list of € @ViewBag.N1 - @ViewBag.N2

Or by using a model:

Controller:

public class MyModel 
{
    public Int32 N1 {get;set;}
    public Int32 N2 {get;set;}
}

public ActionResult Filter(int number1, int number2)
{          
    var result = db.Gifts.Where(c => c.Price > number1 && c.Price <= number2).ToList();     
    return View(new MyModel{N1 = 50, N2 = 100});
}

View:

@model MyModel

@Html.ActionLink("€ 50-100", "Filter", new { number1 = @Model.N1, number2 = @Model.N2 }, null)
<h3> Choose a gift from the list of € @Model.N1 - @Model.N2 </h3>

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