Search code examples
c#htmlasp.net-mvcrazor

Send id to controller from view in option tag


I am trying to create my first web app. I have list of products and I want to sort products by name or price. The possible option I have in <select> tag and I try to use method onchange to send paramteres to my controller and there sort my list of products. When I debug my program I saw that as paramteres is send null value. Have you got some idea how can I resolve my problem?

<p>Sort by:</p>

<select onchange="location = this.value">
   <option value="@Url.Action("SortByString", new { id = "-----" })">-----</option>
   <option value="@Url.Action("SortByString", new { id = "Name" })">Name</option>
   <option value="@Url.Action("SortByString", new { id = "Price" })">Price</option>
</select>

public ActionResult SortByString(string sort){}

And as paramter sort is send null. Thanks.


Solution

  • You should use one of the multiple overloads of Url.Action() method according to your need. In this case, you can use the fourth overload which is specified in this article.

    So you need to change your code as following to pass exactly that parameter which you specified in your action method in the controller (If you don't want to define a custom route for your URL):

    <p>Sort by:</p>
    
    <select onchange="location = this.value">
       <option value="@Url.Action("SortByString", new { sort = "-----" })">-----</option>
       <option value="@Url.Action("SortByString", new { sort = "Name" })">Name</option>
       <option value="@Url.Action("SortByString", new { sort = "Price" })">Price</option>
    </select>
    
    public ActionResult SortByString(string sort){}