更新在mvc4对象的列表 [英] Updating a list of objects in mvc4

查看:80
本文介绍了更新在mvc4对象的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经采取了我一个asp.net应用mvc4有一个问题,它简化了,所以我可以张贴在这里。我的基本问题是,我想送的项目清单到我的查看和编辑的任何项目的复选框,然后发送列表项反馈给控制器,并能最终保存到数据库中。在code被写入现在当我发送名单反馈给控制器的方式,跨越之际,就像它从来没有实例化一个空值。

在code是如下:

 公共类Person
    物业编号作为整数
    物业名称作为字符串
    物业积极作为布尔
末级

在控制器我叫了一个名为BuildPeople类,其实就是一个建立在列表中绕过方式:

 公共类BuildPeople    公共职能GetPersonList()方式列表(人)
        昏暗personList作为新的列表(人)
        personList.Add(GetPerson(1,克里斯,真))
        personList.Add(GetPerson(2,肯,真))
        personList.Add(GetPerson(3,仁,真))
        返回personList
    结束功能    专用功能GetPerson(ID为整数,字符串类型,主动作为布尔)由于人
        昏暗的数p作为新出生
        p.ID = ID
        p.Name =名称
        p.Active =活跃
        返回p
    结束功能
末级

该控制器不仅具有编辑功能:

 进口System.Web.Mvc公共类把PeopleController
    继承控制器    'GET:/人
    功能指数()为的ActionResult
        返回查看()
    结束功能    'GET:/人/编辑/ 5
    功能编辑()为的ActionResult
        昏暗的BP作为新BuildPeople
        昏暗的模型作为新的列表(人)
        模型= bp.GetPersonList
        ViewData.Model =模型
        返回查看()
    结束功能    POST:/人/编辑/ 5
    &所述; HttpPost()>
    功能编辑(BYVAL listPeople方式列表(人))作为的ActionResult
        尝试
            'TODO:添加更新逻辑这里
            如果listPeople是Nothing然后
                不要想结束在这里
                返回查看()
            其他
                要结束了在这里
                昏暗我为整数= listPeople.Count
                返回查看()
            万一
        抓住
            返回查看()
        结束Try
    结束功能
末级

然后在视图如下:

  @ModelType列表(人)
@ code
    ViewData的(标题)=编辑
    布局=〜/查看/共享/ _Layout.vbhtml
结束code< H2>编辑< / H>@using(Html.BeginForm())
    @ Html.AntiForgeryToken()    @< D​​IV CLASS =形横>
        < H4>与人LT; / H4>
        <小时/>
        @For每个项目在模型
        昏暗的CURRENTITEM =项目
            @ Html.HiddenFor(功能(模型)currentitem.ID)
            @ Html.EditorFor(功能(模型)currentitem.Name)
            @ Html.EditorFor(功能(模型)currentitem.Active)
        下一个        < D​​IV CLASS =表单组>
            < D​​IV CLASS =COL-MD-偏移2 COL-MD-10>
                <输入类型=提交值=保存级=BTN BTN-默认的/>
            < / DIV>
        < / DIV>
    < / DIV>
使用完< D​​IV>
    @ Html.ActionLink(返回目录,索引)
< / DIV>


解决方案

所以,你必须有HTML表单是如何工作的,以及MVC模式的粘结剂是如何工作的一些认识。

复选框仅在后数据发送的值回如果他们检查

接下来,在MVC模型绑定将重组集合/列表,只要该领域的命名遵循正确的命名约定对象。

所以,你的循环为每个项目在模型需要生产出正确的名称的项目。

让我们稍微改变你的模型。

 公共类PeopleModel
  公共属性人民名单(人)
  公共属性SelectedPeople方式列表(中的Int64)'假设Person.ID是的Int64
末级

然后,你的改变你的观点的循环,像这样:

 昏暗的ItemIndex作为的Int32 = 0
每个人作为人在Model.People
  @<输入类型=复选框名称='SelectedPeople [@itemIndex]'id='person_@person.ID'value='@person.ID/>
  @<输入类型=隐藏的名字='SelectedPeople [@itemIndex]'值= - 1/>
  的ItemIndex + = 1
下一个

我们把隐藏的元素在里面,因为它会为选中项的字段值。否则,第一个选中的项目将打破指数和模型绑定将停止。

现在在你的控制器的职位处理程序:

 < HttpPost>
公共职能ActionName(型号为PeopleModel)作为的ActionResult  每个ID作为Int64的在model.SelectedPeople
    如果0℃; ID,然后在
      这是一个选择的人的ID - 用它做什么。
    万一
  下一个结束功能

I have taken an issue that I am having with a asp.net mvc4 applications and simplified it so I can post it here. My basic problem is that I am trying to send a list of items to my view and edit the check box of any of the items and then send the list items back to the controller and be able to eventually save to the database. The way the code is written right now when I send the list back to the controller it comes across as a null value just like it was never instantiated.

The code is as follows:

Public Class Person
    Property ID As Integer
    Property Name As String
    Property Active As Boolean
End Class

In the controller I call a class called BuildPeople that is really just a way to build the the list to pass around:

Public Class BuildPeople

    Public Function GetPersonList() As List(Of Person)
        Dim personList As New List(Of Person)
        personList.Add(GetPerson(1, "Chris", True))
        personList.Add(GetPerson(2, "Ken", True))
        personList.Add(GetPerson(3, "Jen", True))
        Return personList
    End Function

    Private Function GetPerson(id As Integer, name As String, active As Boolean) As Person
        Dim p As New Person
        p.ID = id
        p.Name = name
        p.Active = active
        Return p
    End Function  
End Class

The controller only has the edit ability:

    Imports System.Web.Mvc

Public Class PeopleController
    Inherits Controller

    ' GET: /People
    Function Index() As ActionResult
        Return View()
    End Function

    ' GET: /People/Edit/5
    Function Edit() As ActionResult
        Dim bp As New BuildPeople
        Dim model As New List(Of Person)
        model = bp.GetPersonList
        ViewData.Model = model
        Return View()
    End Function

    ' POST: /People/Edit/5
    <HttpPost()>
    Function Edit(ByVal listPeople As List(Of Person)) As ActionResult
        Try
            ' TODO: Add update logic here
            If listPeople Is Nothing Then
                'Don't want to end up here
                Return View()
            Else
                'Want to end up here
                Dim i As Integer = listPeople.Count
                Return View()
            End If
        Catch
            Return View()
        End Try
    End Function
End Class

And then the view is as follows:

@ModelType List(Of Person)
@Code
    ViewData("Title") = "Edit"
    Layout = "~/Views/Shared/_Layout.vbhtml"
End Code

<h2>Edit</h2>

@Using (Html.BeginForm())
    @Html.AntiForgeryToken()

    @<div class="form-horizontal">
        <h4>Person</h4>
        <hr />
        @For Each item In Model
        Dim currentitem = item
            @Html.HiddenFor(Function(model) currentitem.ID)
            @Html.EditorFor(Function(model) currentitem.Name)
            @Html.EditorFor(Function(model) currentitem.Active)
        Next

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
End Using

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

解决方案

So you have to have some understanding of how HTML forms work as well as how the MVC model binder works.

Checkboxes only send a value back in the post data if they are checked.

Next, the model binder in MVC will reconstitute collection/list objects as long as the field naming follows the proper naming convention.

So your loop For Each item In Model needs to produce items with the correct name.

Let's change your model slightly.

Public Class PeopleModel
  Public Property People As List(Of Person)
  Public Property SelectedPeople As List(Of Int64)  ' Assuming Person.ID is Int64
End Class

Then your change your view's loop like so:

Dim itemIndex As Int32 = 0
For Each person As Person In Model.People
  @<input type='checkbox' name='SelectedPeople[@itemIndex]' id='person_@person.ID' value='@person.ID' />
  @<input type='hidden' name='SelectedPeople[@itemIndex]' value='-1' />
  itemIndex += 1
Next

We place the hidden element in there because it will provide a field value for unchecked items. Otherwise the first unchecked item would break the indices and the model binder would stop.

Now in your controller's post handler:

<HttpPost>
Public Function ActionName(model As PeopleModel) As ActionResult

  For Each id As Int64 In model.SelectedPeople
    If 0 < id Then
      ' This is the id of a selected person - do something with it.
    End If
  Next

End Function

这篇关于更新在mvc4对象的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆