Asp.net mvc 如何保存对数据库所做的更改
我有以下编辑操作 在视图中,我有以下代码Asp.net mvc 如何保存对数据库所做的更改,asp.net-mvc,asp.net-core,Asp.net Mvc,Asp.net Core,我有以下编辑操作 在视图中,我有以下代码 <form asp-action="Edit" class="form-horizontal"> <input type="text" asp-for="Code" value="@Model.Code" class="form-control" /> <button class="btn btn-success Product-edit-button" role="button">Save</but
<form asp-action="Edit" class="form-horizontal">
<input type="text" asp-for="Code" value="@Model.Code" class="form-control" />
<button class="btn btn-success Product-edit-button" role="button">Save</button>
</form>
如何在单击按钮时保存对数据库的更改
这是我试过的,编辑模型的样子
public async Task<IActionResult> editModel(int? id)
{
if (id == null)
{
return NotFound();
}
var ProductList = (await ProductService.GetProducts()).ToList();
var Product = ProductList.FirstOrDefault(a => a.ID == id);
if (Product == null)
{
return NotFound();
}
return View(Product);
}
编辑操作如下所示
public async Task<IActionResult> Edit(ProductEditModel editModel)
{
if (id == null)
{
return NotFound();
}
var ProductList = (await ProductService.GetProducts()).ToList();
var Product = ProductList.FirstOrDefault(a => a.ID == id);
if (Product == null)
{
return NotFound();
}
Product.Code = editModel.Code;
ProductService.EditProduct(Product);
return View(Product);
}
您需要另一个接受POST请求并向其发送编辑数据的操作
public async Task<IActionResult> Edit(ProductEditModel editModel)
{
if (id == null)
{
return NotFound();
}
var ProductList = (await ProductService.GetProducts()).ToList();
var Product = ProductList.FirstOrDefault(a => a.ID ==editModel.Id);
if (Product == null)
{
return NotFound();
}
Product.Code=editModel.Code;
ProductService.EditProduct(Product);
return View(Product);
}
观点:
拯救
下面是一个工作演示,如下所示: 1.型号:
public class ProductEditModel
{
public int ID { get; set; }
public string Code { get; set; }
}
2.ViewEdit.cshtml:
@model ProductEditModel
<h4>ProductEditModel</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="ID" />
<div class="form-group">
<label asp-for="Code" class="control-label"></label>
<input asp-for="Code" class="form-control" />
<span asp-validation-for="Code" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</div>
3.控制员:
public class ProductEditModelsController : Controller
{
private readonly YourContext _context;
public ProductEditModelsController(YourContext context)
{
_context = context;
}
// GET: ProductEditModels/Edit/5
//display edit view
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var productEditModel = await _context.ProductEditModel.FindAsync(id);
if (productEditModel == null)
{
return NotFound();
}
return View(productEditModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(ProductEditModel productEditModel)
{
if (ModelState.IsValid)
{
_context.Update(productEditModel);//update model
await _context.SaveChangesAsync();//save to database
return RedirectToAction(nameof(Index));
}
return View(productEditModel);
}
}
public async Task<IActionResult> Index()
{
return View(await _context.ProductEditModel.ToListAsync());
}
4.1背景:
public class YourContext: DbContext
{
public YourContext(DbContextOptions<YourContext> options)
: base(options)
{
}
public DbSet<ProductEditModel> ProductEditModel { get; set; }
}
5.Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddDbContext<YourContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("YourConnnection"))); //connect to sql server
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//...
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Privacy}/{id?}");
});
}
结果:
更新:
1.Index.cshtml:
@model IEnumerable<ProductEditModel>
@{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Code)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Code)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.ID">Edit</a> |
<a asp-action="Details" asp-route-id="@item.ID">Details</a> |
<a asp-action="Delete" asp-route-id="@item.ID">Delete</a>
</td>
</tr>
}
</tbody>
</table>
2.控制器中的索引操作:
public class ProductEditModelsController : Controller
{
private readonly YourContext _context;
public ProductEditModelsController(YourContext context)
{
_context = context;
}
// GET: ProductEditModels/Edit/5
//display edit view
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var productEditModel = await _context.ProductEditModel.FindAsync(id);
if (productEditModel == null)
{
return NotFound();
}
return View(productEditModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(ProductEditModel productEditModel)
{
if (ModelState.IsValid)
{
_context.Update(productEditModel);//update model
await _context.SaveChangesAsync();//save to database
return RedirectToAction(nameof(Index));
}
return View(productEditModel);
}
}
public async Task<IActionResult> Index()
{
return View(await _context.ProductEditModel.ToListAsync());
}
如果您未能成功理解,请先学习下面的mvc教程
参考:
谢谢,我如何传递id,这一行给我的错误id在当前上下文中不存在var Project=ProjectList.FirstOrDefaulta=>a.id==id;?什么是ProductService.EditProductProduct;还有ProjectEditModelMike你能告诉我ProjectEditModel动作是什么样子吗?抱歉,我有点困惑ProjectEditModel是一个类。我认为令人困惑的是在控制器中创建一个新动作。我将在几分钟内更新代码。谢谢迈克,我想看看其他操作的效果。我想看到你更新问题。这是正确的。只需将editModel操作重命名为Edit。实际上,我共享了代码。您的意思是您想要CRUD的全部代码吗?您好,请检查我的答案。如果仍然存在问题,请先学习mvc教程: