4

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

2
  • 1
    your question here is way too broad. There are many ways you can implement this, and it's somewhat dependent on the database you are using (which you haven't identified here). Try identifying a bit of real code you have used that isn't having the desired effect to start off with. Commented Apr 8, 2014 at 11:33
  • I totally understand, however, I was wanting a broad answer. Thank you for taking the time to look into this for me. Commented Apr 15, 2014 at 8:43

2 Answers 2

6

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for all your comments/advice. This really supported me with my application. Chris, that is exactly what I wanted. Thank you
0
[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();    
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.