C # - ASP.net MVC 3- Insert multiple rows into a table

I am new to ASP.net MVC this year.

Question How can I implement a class / representation of a method / model that will accept multiple database attachments?

I understand that I will have to use the model binding method, but I'm not sure how to implement this within my project.

Proposed Answer The solution is a simple example / implementation template for a view using multiple inserts. (Examples of controllers, models, code examples)

Sceanrio example . I have a product table, I would like to insert / create 11 types of products. Therefore, inserting 11 times into the product table in my method / view.

I am studying the search for possible solutions using:

https://stackoverflow.com/search?q=model+binding+to+a+collection

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

This is helpful, but not helpful regarding my problem.

If anyone could advise me on this, I would be very grateful. Thank you for your time.

+4
source share
2 answers

First off, I agree with @AndrewCounts. You doubt a fairly broad question, and it will be difficult to give answers to quality answers. However, I can give you general guidance, which I hope will keep you going.

, , , . , :

GET

public ActionResult CreateMyModels()
{
    var myModels = new List<MyModel>();
    for (var i = 0; i < totalItems; i++)
    {
        myModels.Add(new MyModel());
    }
    return View(myModels)
}

@model List<Namespace.To.MyModel>

@using (Html.BeginForm())
{
    for (var i = 0; i < Model.Count(); i++)
    {
        // Model fields here, i.e.
        // @Html.EditorFor(m => m[i].SomeField)
    }

    <button type="submit">Submit</button>
}

for foreach , . , Html.EditorFor, Razor , .

undefined , . Modelbinder name :

ListName[index].FieldName

POST :

[HttpPost]
public ActionResult CreateMyModels(List<MyModel> myModels)

:

myModels[0].FirstField
myModels[0].SecondField
...
myModels[1].FirstField
...

JavaScript, , , name .

, POST . , . Entity Framework , MVC . , :

[HttpPost]
public ActionResult CreateMyModels(List<MyModel> myModels)
{
    if (ModelState.IsValid)
    {
        foreach (var myModel in myModels)
        {
            db.MyModels.Add(myModel);
        }
        db.SaveChanges();

        return RedirectToAction("Index");
    }

    return View(myModels);
}
+5
[HttpPost]    
public ActionResult Index(List<Employee> employees)    
{    
    CompanyEntities DbCompany = new CompanyEntities();

    foreach (Employee Emp in employees)    
    {    
        Employee Existed_Emp = DbCompany.Employees.Find(Emp.ID);    
        Existed_Emp.Name = Emp.Name;    
        Existed_Emp.Gender = Emp.Gender;    
        Existed_Emp.Company = Emp.Company;    
    }    
    DbCompany.SaveChanges();    
    return View();    
}
0

Source: https://habr.com/ru/post/1535539/


All Articles