在ASP.Net MVC中进行插入和更新操作的解决方法可以使用实体框架(Entity Framework)来简化数据库操作。下面是一个包含代码示例的解决方法:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public class MyDbContext : DbContext
{
public DbSet Persons { get; set; }
}
public class PersonController : Controller
{
private MyDbContext _dbContext;
public PersonController()
{
_dbContext = new MyDbContext();
}
// 插入数据
public ActionResult Create(Person person)
{
_dbContext.Persons.Add(person);
_dbContext.SaveChanges();
return RedirectToAction("Index");
}
// 更新数据
public ActionResult Edit(int id)
{
Person person = _dbContext.Persons.Find(id);
return View(person);
}
[HttpPost]
public ActionResult Edit(Person person)
{
_dbContext.Entry(person).State = EntityState.Modified;
_dbContext.SaveChanges();
return RedirectToAction("Index");
}
}
Create.cshtml:
@model Person
@using (Html.BeginForm("Create", "Person", FormMethod.Post))
{
@Html.LabelFor(model => model.Name)
@Html.TextBoxFor(model => model.Name)
@Html.LabelFor(model => model.Age)
@Html.TextBoxFor(model => model.Age)
}
Edit.cshtml:
@model Person
@using (Html.BeginForm("Edit", "Person", FormMethod.Post))
{
@Html.HiddenFor(model => model.Id)
@Html.LabelFor(model => model.Name)
@Html.TextBoxFor(model => model.Name)
@Html.LabelFor(model => model.Age)
@Html.TextBoxFor(model => model.Age)
}
在上述代码示例中,通过使用实体框架,我们可以很方便地进行插入和更新操作。在插入操作中,我们将实体添加到数据库上下文中并保存更改。在更新操作中,我们使用Entry
方法将实体的状态标记为修改,并保存更改。