-1

In my ASP.NET Core application, I have an ASP.NET MVC View which displays a list of products. (I guess this applies to other versions of MVC as well).

When I select an item from this list and submit the page, I want the selected product ID to be bound to a ViewModel property in the action method of the controller. I am using POST for this.

I do NOT want to use SelectList for rendering the list of products due to some formatting issues. Therefore I am looping over the list in my view.

How can I bind the selected product with the ProductId property of the inbound ViewModel object?

SirG
  • 301
  • 3
  • 13

1 Answers1

2

It's unclear what you mean by "select an item from this list and submit the page". Are you picking an item, potentially filling out more fields, and then submitting the whole shebang, or does picking an item constitute submitting the form. Depending on the situation there's a few approaches:

  1. If picking an item submits the form, then you can simply make the "Select" button a submit button and give it a name and value. For example:

    Item 1 <button type="submit" name="ProductId" value="1">Select</button>
    

    Whichever "Select" button is clicked, then, will have its value posted as ProductId.

  2. If you need to pick an item while remaining on the page to fill out other fields, then you can use radio buttons as an alternative to a select list. This is similar to approach above, except you will not instantly post the form. Your inputs would look similar though:

    <label>
        <input type="radio" name="ProductId" value="1"> Item 1
    </label>
    <label>
        <input type="radio" name="ProductId" value="2"> Item 2
    </label>
    ...
    
  3. Finally, if you need to not instantly submit and you do not want to use radio buttons either, then your only real option is using JavaScript to set a hidden input. You would bind to the click event of your "Select" button or whatever and then set a hidden input with name="ProductId" to the appropriate value. Then, when you finally submit the form, the value of the hidden input will be posted as ProductId.

Chris Pratt
  • 207,690
  • 31
  • 326
  • 382
  • Thanks for the answer, Chris. My case is scenario 3. Will test it out tomorrow and accept your answer. – SirG Nov 18 '16 at 19:47
  • Confirmed that it is working. Thanks again Chris. Much appreciated. – SirG Nov 19 '16 at 16:11