POST a form array without successful

后端 未结 5 1269
误落风尘
误落风尘 2020-11-21 05:07

I\'m developing an ASP.NET MVC 5 web with C# and .NET Framework 4.5.1.

I have this form in a cshtml file:

@model MyProduct.         


        
5条回答
  •  长发绾君心
    2020-11-21 05:49

    you can visit this article for complete source code with a video tutorial.

    you have to create an action first, from where we can pass the list of object

    [HttpGet]
    public ActionResult Index()
    {
        List model = new List();
        using (MyDatabaseEntities dc = new MyDatabaseEntities())
        {
            model = dc.Contacts.ToList();
        }
        return View(model);
    }
    

    then we need to create a view for that action

    @model List
    @{
        ViewBag.Title = "Update multiple row at once Using MVC 4 and EF ";
    }
    @using (@Html.BeginForm("Index","Home", FormMethod.Post))
    {
        
            @for (int i = 0; i < Model.Count; i++)
            {
                
            }
        
    Contact Person Contact No Email ID
    @Html.HiddenFor(model => model[i].ContactID) @Html.EditorFor(model => model[i].ContactPerson) @Html.EditorFor(model => model[i].Contactno) @Html.EditorFor(model => model[i].EmailID)

    @ViewBag.Message

    } @section Scripts{ @Scripts.Render("~/bundles/jqueryval") }

    and then we have to write code for save the list of object to the database

    [HttpPost]
    public ActionResult Index(List list)
    {  
        if (ModelState.IsValid)
        {
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                foreach (var i in list)
                {
                    var c = dc.Contacts.Where(a =>a.ContactID.Equals(i.ContactID)).FirstOrDefault();
                    if (c != null)
                    {
                        c.ContactPerson = i.ContactPerson;
                        c.Contactno = i.Contactno;
                        c.EmailID = i.EmailID;
                    }
                }
                dc.SaveChanges();
            }
            ViewBag.Message = "Successfully Updated.";
            return View(list);
        }
        else
        {
            ViewBag.Message = "Failed ! Please try again.";
            return View(list);
        }
    }
    

提交回复
热议问题