asp.net mvc添加数据
时间: 2023-07-25 08:05:26 浏览: 68
要 ASP.NET MVC 中添加数据,你需要遵循以下步骤:
1. 创建一个模型类,定义你要添加的数据的属性,例如:
```csharp
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
```
2. 创建一个控制器类,并添加一个方法来处理添加数据的请求,例如:
```csharp
public class ProductsController : Controller
{
private readonly ApplicationDbContext _context;
public ProductsController(ApplicationDbContext context)
{
_context = context;
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Product product)
{
if (ModelState.IsValid)
{
_context.Add(product);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(product);
}
}
```
3. 创建一个视图来显示添加数据的表单,例如:
```html
@model Product
<form asp-action="Create">
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Price" class="control-label"></label>
<input asp-for="Price" class="form-control" />
<span asp-validation-for="Price" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
```
4. 添加路由,以便能够从浏览器中访问到添加数据的页面,例如:
```csharp
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
name: "create",
pattern: "products/create",
defaults: new { controller = "Products", action = "Create" });
});
```
现在你可以通过访问 /products/create 来打开添加数据的页面,在表单中输入数据并提交,数据将会被添加到数据库中。