我无法从ASP.NET MVC将数据插入数据库中

时间:2018-11-04 11:23:13

标签: c# asp.net-mvc database

我的数据没有插入数据库,我也不知道为什么,一切正常。即使我直接将数据输入数据库,它也会显示在网页上,但是当我想通过网页输入数据时,它不会产生任何响应,并且数据保持不变(未输入数据)。

这是我的控制器:

// GET: Hostel/Create
public ActionResult Create()
{
     return View();
}

// POST: Hostel/Create
[HttpPost]
public ActionResult Create(Hostel collection)
{
        try
        {
            // TODO: Add insert logic here
            List<object> list = new List<object>();
            list.Add(collection.H_Name);
            list.Add(collection.H_Phone);
            list.Add(collection.H_Description);
            list.Add(collection.H_TotalBedrooms);
            list.Add(collection.H_WifiCharges);
            list.Add(collection.H_SecurityCharges);
            list.Add(collection.H_MonthyRent);
            list.Add(collection.H_Image);
            list.Add(collection.H_Avaliablity);

            object[] listItems = list.ToArray();
            int cmnd = db.Database.ExecuteSqlCommand("insert into Hostel (H_Name, H_Phone, H_Description, H_TotalBedrooms, H_WifiCharges, H_SecurityCharges, H_MonthyRent, H_Image, H_Avaliablity) values (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9)", listItems);

            if(cmnd > 0)
            {
                ViewBag.msg = "User Added";
            }

            return View();
        }
        catch
        {
            return View();
        }
}

1 个答案:

答案 0 :(得分:0)

// POST: Hostel/Create
    [HttpPost]
    public ActionResult Create(Hostel collection)
    {
        try
        {
            // TODO: Add insert logic here

            //simply remove query and let entity framework to help you with that 
            db.Hostels.Add(collection);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }