1

我有一个模型women,它是我的数据库上下文的一部分,womenEditmodel还有一个包含项目列表的视图模型women。我正在使用 apartialview循环遍历此列表并在我的视图中显示可编辑的网格或列表。这些是我的模型:

public class Women
{
    public string ID { get; set; }
    public string FirstName {get; set;}
    public string LastName {get; set;}
}

public class WomenEditModel
{
    public List<Women> WomenList { get; set; }
}

我的视图有这个循环用于注入我的视图行以获取women记录

@foreach (Women women in Model.Womens)
{
    Html.RenderPartial("WomenEditor", women);
}

我使用table. 因此,现在用户可以编辑列表并发布或保存更改。

我的局部视图看起来像:

@model XXX.Models.Women

@using (Html.BeginCollectionItem("Women")) {                
    <td>
        @Html.HiddenFor(model => model.ID)
    </td>
    <td>
        @Html.TextBoxFor(model => model.FirstName)
        @Html.ValidationMessageFor(model => model.FirstName)
    </td>
    <td>
        @Html.TextBoxFor(model => model.LastName)
        @Html.ValidationMessageFor(model => model.LastName)
    </td>        
}

我的 http post 操作方法如下所示

[HttpPost]
public ActionResult PostWomen(WomenEditModel model)
{
    /*I need to iterate through the returned list and save all
    changes to the db.*/

    return RedirectToAction("Index");
}

我如何循环通过WomenEditModel后操作方法收到的模型并将对女性列表的更改保存回数据库?

提前致谢!!

4

2 回答 2

1

我刚回到我的机器。如果您还没有,这里是如何实现它的。

呈现列表的我的操作

    public ActionResult Index()
    {
        List<Women> womens = new List<Women>
            {
                new Women
                    {
                         Id=1,
                         FirstName = "Women1",
                         LastName = "Lastname1"
                    },
                new Women
                    {
                         Id=2,
                         FirstName = "Women2",
                         LastName = "Lastname2"
                    }
            };
        WomenList womenList=new WomenList();
        womenList.Womens = womens;
        return View(womenList);
    }

发布列表的操作。

    public ActionResult SaveWomens(List<Women> womenList)
    {
        System.Diagnostics.Debugger.Break();
        //Your save logic goes here
        return View("");
    }

部分视图(不知道是否需要)

@model List<MvcApplication1.Models.Women>
<table>
    @for (var i = 0; i < Model.Count; i++)
    {

        <tr>
            <td>
                @Html.TextBoxFor(m => m[i].Id)
            </td>
            <td>@Html.TextBoxFor(m => m[i].FirstName)
            </td>
            <td>@Html.TextBoxFor(m => m[i].LastName)
            </td>
        </tr> 
    }
</table>

这是视图

@model MvcApplication1.Models.WomenList
@{
    ViewBag.Title = "Home Page";
}
@section featured {
}
@using (Html.BeginForm("SaveWomens", "Home", FormMethod.Post))
{ 
    @Html.Partial("_Women", Model.Womens)

    <input type="submit" value="save" />
}
于 2013-08-27T14:43:14.643 回答
0

您可以按如下方式实现

 foreach (var item in womenList)
 {
     var obj = new Womens();
     //Assign values to obj for eg: obj.prop = item.prop
     dataContext.Womens.AddObject(obj);                  
 }
 dataContext.SaveChanges();
于 2013-08-27T16:03:36.193 回答