【发布时间】:2017-03-07 23:53:44
【问题描述】:
为我的项目寻求帮助。尝试使用输入表单将对象添加到数据库。这是我的代码:
家庭控制器
public class HomeController : Controller
{
EventsContext db = new EventsContext();
public ActionResult Index()
{
IEnumerable<Event> events = db.Events;
ViewBag.Events = events;
return View();
}
[HttpGet]
public ActionResult CreateEvent()
{
return View();
}
[HttpPost]
public ActionResult CreateEvent(AddEvent addEvent)
{
db.AddEvents.Add(addEvent);
db.SaveChanges();
return View("index");
}
}
目前我正在尝试对 AddEventId 进行硬编码并在表单中提供它,稍后我将对其进行更改。 这是输入表单:
<form method="post" action="">
<table>
<tr>
<td><p>Id :</p></td>
<td><input type="text" name="AddEventId" /> </td>
</tr>
<tr>
<td><p>Title :</p></td>
<td><input type="text" name="Title" /> </td>
</tr>
<tr>
<td><p>Date :</p></td>
<td><input type="text" name="Date" /> </td>
</tr>
<tr>
<td><p>Time :</p></td>
<td><input type="text" name="Time" /> </td>
</tr>
<tr>
<td><p>Address :</p></td>
<td><input type="text" name="Location" /></td>
<tr>
<td><p>Lecturer:</p></td>
<td><input type="text" name="Responsible" /> </td>
</tr>
<tr><td><input type="submit" value="Submit" /> </td><td></td></tr>
</table>
</form>
AddEvent 类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PhClub.Models
{
public class AddEvent
{
public int AddEventId { get; set; }
public string Title { get; set; }
public string Date { get; set; }
public string Time { get; set; }
public string Location { get; set; }
public string Responsible { get; set; }
}
}
事件类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PhClub.Models
{
public class Event
{
public int Id { get; set; }
public string Title { get; set; }
public string Date { get; set; }
public string Time { get; set; }
public string Location { get; set; }
public string Responsible { get; set; }
}
}
它适用于硬编码事件
public class EventDbInitializer : DropCreateDatabaseAlways<EventsContext>
{
protected override void Seed(EventsContext db)
{
db.Events.Add(new Event { Title = "Name of Event", Date = "18/11/2017", Time = "20:00", Location = "Adress", Responsible = "Name" });
db.Events.Add(new Event { Title = "Name of Event", Date = "03/03/2017", Time = "19:00", Location = "Adress", Responsible = "Name2" });
//db.Events.Add(new Event { Title = "Title3, Date = "04/03/2017", Time = "217:00", Location = "School", Responsible = "Name"});
base.Seed(db);
}
}
如果我在按下提交后理解正确,则应使用 CreateEvent post 方法,并且应将 Event 对象的所有元素传递给数据库中的 create 和 Event。之后,它应该填充在页面上。但是,新事件没有。我没看到什么?
【问题讨论】:
标签: c# asp.net-mvc