如何使用viewmodel(IEnumerable)在ASP.NET MVC 4中更新我的数据库

时间:2014-11-05 04:00:19

标签: c# asp.net-mvc asp.net-mvc-4

{WV_DeviceReg, WV_DevEventLog, WV_DevSystemLog, WV_DeviceConfig}是来自ADO.NET Entity Framework的模型。

视图模型

namespace MvcWebVms.Models
{
    public class HomeViewModels
    {
        public IEnumerable<WV_DeviceReg> DeviceReg { get; set; }
        public IEnumerable<WV_DevEventLog> DevEventLog { get; set; }
        public IEnumerable<WV_DevSystemLog> DevSystemLog { get; set; }
        public IEnumerable<WV_DeviceConfig> DeviceConfig { get; set; }
    }
}

查看

@model MvcWebVms.Models.HomeViewModels

@using (Html.BeginForm()){

    <div>

       @foreach (var item in Model.DeviceConfig) {

             @Html.HiddenFor(modelItem => item.FieldName)
             @Html.HiddenFor(modelItem => item.DeviceID_F)

            <div class="editor-label">
                    @Html.DisplayFor(modelItem => item.FieldName)
            </div>
            <div class="editor-field">
                    @Html.EditorFor(modelItem => item.FieldValue)
            </div>

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

    </div>
}

控制器

public ActionResult Setting(string id)
{
    HomeServices service = new HomeServices();
    return View(service.GetDeviceSettingAT(id));
}

public WVDBEntities wvdb = new WVDBEntities();

[HttpPost]
public ActionResult Setting(HomeViewModels viewModels)
{

    if (ModelState.IsValid)
    {

    foreach (????????????)
        {
           ????????????????
        }
        wvdb.SaveChanges();
        return View(viewModels);
    }
    else
    {
        return View();
    }

}

WV_DeviceConfig { FieldName(PK), DeviceID_F(PK), FieldValue, ServerTime }

FieldName的键映射FieldValue的值

问:如何使用foreach来更新我的数据库?

1 个答案:

答案 0 :(得分:1)

我认为首先你要将你的foreach循环更改为传统的for循环并像这样回发一个List:

@for (int i = 0; i < Model.DeviceConfig.Count(); i ++) {
       @Html.HiddenFor(m => m.DeviceConfig[i].FieldName)
 //etc.. same thing for all hidden/input fields

并且您的操作方法可以接受类似的列表

[HttpPost]
public ActionResult Setting(List<DeviceConfig> DeviceConfigList)

然后您可以执行以下操作来更新数据库

foreach (var item in DeviceConfigList)
    {
      db.Entry(item).State = EntityState.Modified;
    }
db.SaveChanges();