user3510598
user3510598

Reputation: 43

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

I am new to ASP.net MVC this year.

Question How would I go about implementing a method/model class/view that would accept multiple inserts into the database?

I understand I will have to utilise the model binding technique, but I am unsure of how to implement this within my project.

Proposed Answer A solution in mind would be a simple example/template of implementing a view using multiple inserts. (Controller, Model, View- code examples)

Example Sceanrio: I have a product table, I would like to insert/create 11 product types. Therefore inserting 11 times into the product table within my method/view.

I have been investigating an exploring 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

These are useful, but not helpful in regards to my problem.

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

Upvotes: 4

Views: 10658

Answers (2)

mohita
mohita

Reputation: 201

[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();    
}

Upvotes: 0

Chris Pratt
Chris Pratt

Reputation: 239440

First, I agree with @AndrewCounts. You question is quite broad and it will be difficult to provide good quality answers. However, I can give you some general guidance, that will hopefully get you going.

In general, if you're talking about inserting multiple rows, you're really just talking about providing a form with a set of repeating fields that submits as a list of objects. If you have a defined number of items, you can pass a list of objects as your model for your view:

GET action

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

View

@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>
}

It's important to use for rather than foreach here, so that you get an indexer. If you pass an indexed item to things like Html.EditorFor, Razor will properly generate the field names so they are posted as a list.

If you have an undefined or variable number of items, then you're responsible for generating the proper field names. The modelbinder expects the following format for the name attribute of fields within a list of items:

ListName[index].FieldName

If your POST action signature looked like:

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

Then your fields would need to be named like:

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

In the JavaScript that you use to render the set of fields to the page, you'll need to ensure that the name attributes are set properly.

Whichever methodology you employ, your POST action is the same. You'll receive a list of things, and you'll need to insert each one. I'm going to assume Entity Framework for this example, since most MVC application will use that. You'll need to obviously modify this code to fit your own situation:

[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);
}

Upvotes: 6

Related Questions