How can I do model binding and data display at the same time using the same model.list?

*爱你&永不变心* 提交于 2019-12-04 21:53:48

I think you need change your view as follows:

@model IEnumerable<UserRemarks>

@using(Html.BeginForm())
{
    for(int i=0; i<@Model.Count; i++) 
    {
        <table> 
        <tr> 
            <td align="center"><font class="font_table_content">@Html.TextboxFor(m => m[i].Id)</font></td> 
            <td align="center"><font class="font_table_content">@Html.TextboxFor(m => m[i].Full_Name</font></td> 
            <td align="center"><font class="font_table_content">@Html.TextboxFor(m => m[i].Remarks")</font></td>
        </tr>
        </table>
    }

    <input type="submit" value="submit"/>
}

Then the get action should be changed to:

[HttpGet] 
public ActionResult RemarksTest() 
    { 
         List<UserRermarks> model = LoadTheList();
         return View(model);
    }

And the post action changed to:

[HttpPost] 
public ActionResult RemarksTest(IEnumerable<UserRemarks> model) 
    { 
         foreach (var remarks in model) 
         { 
               //do something to save the input data into code. 
         } 

         return View(model); 
    } 

Unfortunately I don't have visual studio on the computer I am working on so I am unable to test the above but the logic should be correct so if a problem occurs it may just be that I have typed something slightly a miss.

Hope this works for you.

In your GET controller action you could store the list in TempData:

[HttpGet]
public ActionResult RemarksTest()
{
     RemarksModel model = new RemarksModel();
     model.List = LoadTheList();
     TempData['List'] = model.List;
     return View(model);
}

Then in your POST action retrieve it with:

var myList = TempData['List']

If your app is stateless (i.e. no sessions), then you can use a cookie-based TempData provider.

The problem is you are just displaying the values. To post values to server back, you need to have some inputs (like, textbox,checkbox,radiobutton,hiddenfields). In your case you can define hidden fields ,so that model binder will bind them to List of UserRemarks.

Follow http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx to bind a list to model.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!