繁体   English   中英

插入多条记录MVC

[英]Insert Multiple Records MVC

我正在MVC 5中插入多个记录。我一直在这里使用本教程作为开始: http : //dotnetawesome.com/mvc/insert-multiple-record-to-database-at-a-time-aspnet- mvc4 ,但是我的情况有点不同。

我正在从现有表中提取数据,然后添加4列数据。 现有表中的数据和新的4列数据都将添加到新表中。 我不需要上面的教程中所示的“添加新行”。

我已经完成了所有设置,但是在我的文章中,我的模型恢复为空白,我不确定为什么。

// GET:
public ActionResult PCP2(string sortOrder, string currentFilter, string searchString, int? page, string pcp, string location, string locationToSchedule, string scheduleVisitType, string approvedBy)
{
    ViewBag.Location = location;
    ViewBag.LocationType = locationToSchedule;
    ViewBag.VisitType = scheduleVisitType;
    ViewBag.ApprovedBy = approvedBy;

    //query db   
    var model = from n in db.DataDump
                where n.PCP == pcp
                orderby n.MemberName
                select new SnapshotVM()
                {
                    SubscriberID = n.SubscriberID,
                    MemberName = n.MemberName,
                    DateOfBirth = n.DateOfBirth,
                    PCP = n.PCP,
                    IPA = n.IPA,
                    App = n.App,
                    RemainingOpportunities = n.RemainingOpportunities,
                    TID = 0,
                    Location = "",
                    ApprovedBy = "",
                    LocationToSchedule = "",
                    ScheduleVisitType = "",
                    Guid = Guid.NewGuid(),
                    ParentCompany = "XXX",
                    location = location,
                    locationToSchedule = locationToSchedule,
                    scheduleVisitType = scheduleVisitType,
                    approvedBy = approvedBy
                };

    return View(model.ToList());
}

// POST: 
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PCP(List<SnapshotVM> model)
{
    var addMember = newTD();            
    // save data
    using (var context = new TDAllDb())
        foreach (var item in model)                     
        {
            //Add Member                    
            addMember.SubscriberID = item.SubscriberID;
            addMember.MemberName = item.MemberName;
            addMember.DateOfBirth = item.DateOfBirth;
            addMember.PCP = item.PCP;
            addMember.IPA = item.IPA;
            addMember.App = item.App;
            addMember.RemainingOpportunities = item.RemainingOpportunities;
            addMember.Location = item.Location;
            addMember.ApprovedBy = item.ApprovedBy;
            addMember.LocationToSchedule = item.LocationToSchedule;
            addMember.ScheduleVisitType = item.ScheduleVisitType;
            addMember.Guid = Guid.NewGuid();
            addMember.DateCreated = System.DateTime.Now.AddHours(-7);
            addMember.ParentCompany = "XXX";
            context.TD.Add(addMember);
            context.SaveChanges();          
        }                  

    return View(model);
}

视图:

<table>
@if (Model != null && Model.Count > 0)
{
    int j= 0;
    foreach (var item in Model)
    {
        j = j + 1;
        <tr>
            <td>@j</td>
            <td>
                @item.SubscriberID
            </td>
            <td>
                @item.MemberName
            </td>
            <td>
                @if (item.DateOfBirth != null)
                {
                    @item.DateOfBirth.Value.ToShortDateString()
                }
            </td>
            <td>
                @item.IPA
            </td>
            <td>
                @item.App
            </td>
            <td>
                @Html.DropDownList("[" + @j + "].Location", (IEnumerable<SelectListItem>)ViewBag.location, "", new { @class = "input-sm" })
                @Html.Hidden("[" + @j + "].SubscriberID", item.SubscriberID)
                @Html.Hidden("[" + @j + "].MemberName", item.MemberName)
                @Html.Hidden("[" + @j + "].DateOfBirth", item.DateOfBirth)
                @Html.Hidden("[" + @j + "].PCP", item.PCP)
                @Html.Hidden("[" + @j + "].IPA", item.IPA)
                @Html.Hidden("[" + @j + "].App", item.App)
                @Html.Hidden("[" + @j + "].RemainingOpportunities", item.RemainingOpportunities)
                <td>
                    @Html.DropDownList("[" + @j + "].LocationToSchedule", new List<SelectListItem>
                    {
                        new SelectListItem {Text = "Home", Value = "Home"},
                        new SelectListItem {Text = "Office", Value = "Office"},
                    }, 
                    "", 
                    new { @class = "form-control" })
                </td>
                <td>
                    @Html.DropDownList("[" + @j + "].ScheduleVisitType", new List<SelectListItem>
                    {
                        new SelectListItem {Text = "Screening", Value = "Screening"},
                        new SelectListItem {Text = "Hold", Value = "Hold"},
                    }, 
                    "", 
                    new { @class = "form-control" })
                </td>
                <td>
                    @Html.DropDownList("[" + @j + "].ApprovedBy", new List<SelectListItem>
                    {
                        new SelectListItem {Text = "XXX", Value = "XXX"},
                        new SelectListItem {Text = "YYY", Value = "YYY"},
                    },
                    "", 
                    new { @class = "form-control" })
                </td>
                <td></td>
            </td>
        </tr>
    }
}
</table>
<input type="submit" value="Save Changes" class="btn btn-success" />

视图模型

public class SnapshotVM
{
    [Key]
    [Required]
    [StringLength(255)]
    [DisplayName("Subscriber ID")]
    public string SubscriberID { get; set; }
    [StringLength(255)]
    public string IPA { get; set; }
    [StringLength(255)]
    [DisplayName("Member Name")]
    public string MemberName { get; set; }
    [DisplayName("DOB")]
    public DateTime? DateOfBirth { get; set; }
    [StringLength(255)]
    public string App { get; set; }
    [DisplayName("Rem. Opp.")]
    public int? RemainingOpportunities { get; set; }
    [StringLength(255)]
    public string PCP { get; set; }

    [Key]       
    public int? TID { get; set; }
    [Required]
    [StringLength(50)]
    [DisplayName("*Location")]
    public string Location { get; set; }
    [DisplayName("Parent Company")]
    public string ParentCompany { get; set; }        
    [StringLength(255)]
    [DisplayName("Approved By")]
    public string ApprovedBy { get; set; }        
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public Guid? Guid { get; set; }
    [StringLength(25)]
    [DisplayName("Type of Visit to Schedule")]
    public string ScheduleVisitType { get; set; }
    [StringLength(15)]
    [DisplayName("Location to Schedule")]
    public string LocationToSchedule { get; set; }
    public DateTime? DateCreated { get; set; }
    public IEnumerable<SelectListItem> PCPList { get; set; }
    public string location { get; set; }
    public string locationToSchedule { get; set; }
    public string scheduleVisitType { get; set; }
    public string approvedBy { get; set; }
}

我收到的错误是:

{"Object reference not set to an instance of an object."}

在模型的“发布”中...

foreach (var item in model)

我想念什么?

TIA!


编辑

我将字段更新为HiddenFor和DropDownListFor(例如:@ Html.HiddenFor(m => item.SubscriberID)),但出现了新错误:

System.StackOverflowException was unhandled
Message: An unhandled exception of type 'System.StackOverflowException' occurred in System.Web.dll

Make sure you don't have an infinite loop or recursion.

当我在下拉菜单中选择选项时,会在“获取”上发生此错误。 我在源文件中指出,这些字段未使用计数编制索引。

 @if (Model != null && Model.Count > 0)
 {
     int j= 0;
     foreach (var item in Model)
     {
         @Html.DropDownListFor(m => item.Location, (IEnumerable<SelectListItem>)ViewBag.location, "", new { @class = "input-sm" })
         @Html.HiddenFor(m => item.SubscriberID)
         @Html.HiddenFor(m => item.MemberName)
         @Html.HiddenFor(m => item.DateOfBirth)
         @Html.HiddenFor(m => item.PCP)
         @Html.HiddenFor(m => item.IPA)
         @Html.HiddenFor(m => item.App)
         @Html.HiddenFor(m => item.RemainingOpportunities)

产生这个,名称/ ID上没有索引:

<input id="item_SubscriberID" name="item.SubscriberID" type="hidden" value="123456" />
<input id="item_MemberName" name="item.MemberName" type="hidden" value="FULL NAME" />
<input id="item_DateOfBirth" name="item.DateOfBirth" type="hidden" value="1/15/1900" />
<input id="item_PCP" name="item.PCP" type="hidden" value="NAME" />
<input id="item_IPA" name="item.IPA" type="hidden" value="Y" />
<input id="item_App" name="item.App" type="hidden" value="XXX" />
<input id="item_RemainingOpportunities" name="item.RemainingOpportunities" type="hidden" value="0" />

没有索引似乎并不正确。 我想念什么? 我已经为此工作了几个小时,对此我开始有点眼花cross乱。

您已将j值增加到j = j + 1; 在for循环中,由于生成的名称分别为“ [1] .SubscriberID”,“ [2] .SubscriberID”。 由于模型集合在后期操作中从第0个索引绑定,因此在您的情况下,模型将作为null接收。

另一点-您可以使用HiddenFor和DropDownListFor扩展,它们会自动生成输入控件的相应ID和名称属性。 那将不需要硬编码的索引名称[" + @j + "]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM