View to Controller in mvc3

前端 未结 1 672
生来不讨喜
生来不讨喜 2021-01-24 08:27

I have a problem on passing values from view to controller

Here is my view:

 @model  IEnumerable

        
相关标签:
1条回答
  • 2021-01-24 09:00

    You need to index the Html.*For items as such;

    @Html.RadioButtonFor(m => m[i].SelectedOption, item.Option3, item)
    

    To make things simplier, i'd probably get rid of the foreach & and separate i declaration and use the following;

    @for(int i=0; i < Model.Count; i++)
    {
        @Html.HiddenFor(m => m[i].QuestionID) 
        @Html.RadioButtonFor(m => m[i].SelectedOption, Model[i].Option3, Model[i])
    }
    

    etc.

    Indexing like this will cause the html to be rendered with the indexing intact:

    <input type='hidden' name=[0].'QuestionId' />
    <input type='hidden' name=[1].'QuestionId' />
    <input type='hidden' name=[2].'QuestionId' />
    

    Rather than what you're doing currently, which ends up rendering as so;

    <input type='hidden' name='QuestionId' />
    <input type='hidden' name='QuestionId' />
    <input type='hidden' name='QuestionId' />
    

    Without the indexing, each form field is given the same name, so you're controller is going to think only one was returned.

    0 讨论(0)
提交回复
热议问题