0

I want to do insert multiple input with same name with entity framework. I try this but not work

Model

public class Skill
    {
       [Key]
        public int skill_id { get; set; }


        public string skill_name { get; set; }
    }

View

@model WebApplication1.Models.Skill

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()


    <input type="text" name="skill_name[0]" id="skill_name[0]" />

    <input type="text" name="skill_name[1]" id="skill_name[1]" />

    <input type="submit" value="Submit" />

}

Controller

ProductContext db = new ProductContext();

[HttpPost]
    public ActionResult Save(IList<Skill> skills)
    {
        foreach (var item in skills)
        {
            db.Skills.Add(skills);
            db.SaveChanges();
        }
        return RedirectToAction("index");
    }

dbContext

public class ProductContext : DbContext
    {
        public DbSet<Skill> Skills { get; set; }
    }

How could I do? I find this https://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/ but this tutorial does not have controller example for insert

Heimi
  • 126
  • 1
  • 12
coder_rebirth
  • 57
  • 1
  • 9
  • Your model does not contain a property named `Skills`. What are you trying to bind to (your code makes no sense). Your model does not contain a collection item, and you only saving one object anyway. –  Nov 25 '17 at 04:35
  • Skills is from dbSet in dbContext – coder_rebirth Nov 25 '17 at 04:37
  • I know! But what are you trying to do here - insert multiple instance of `Skill`? –  Nov 25 '17 at 04:38
  • insert multiple instance to "skill_name" field in table Skill – coder_rebirth Nov 25 '17 at 04:39
  • I suggest you read [this answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943) in detail to understand how to generate a view and bind to a collection. And if your wanting to dynamically add (and remove) items, then refer [this answer](http://stackoverflow.com/questions/40539321/partial-view-passing-a-collection-using-the-html-begincollectionitem-helper/40541892#40541892) –  Nov 25 '17 at 04:40

1 Answers1

1

Change

public string skill_name { get; set; }

to

public string[] skill_name { get; set; }

Then Change the Save action method as follows

[HttpPost]
public ActionResult Save(Skill skills)
{
    foreach (var skillName in skills.skill_name)
    { 
       Skill skill = new Skill(); 
       skill.skill_name = skillName;     
       db.Skills.Add(skill);
       db.SaveChanges();
    }
  return RedirectToAction("index");
}
Abhilash Ravindran C K
  • 1,818
  • 2
  • 13
  • 22