mvc之添加数据

添加数据

回显:在input中  value="<%=request.getParamter(”name“)==null?”“:request.getParamter(”name“)%>"

同上

检查是否name被占用

调用 CustomerDAO的getCountWithName(String name)获取name在数据库是否存在

long count=CustomerDAO.getCountWithName(name);

if(count>0){

request.setAttribute(”message“,“用户名”+name+”已存在“);

return;

}

若被占用,则提示

<%

        Object msg=request.getAttribute("message");

            if(msg!=null){

   %>

<br>

<font color="red"><%=msg%></font>

<br>

<%

}

%>

使用重定向可以避免表单的重复提交

要 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 来打开添加数据的页面,在表单中输入数据并提交,数据将会被添加数据库中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值