ASP.NETMVC中更新数据表中当前行并添加新记录的方法。
创始人
2024-09-19 09:01:14
0
  1. 首先,在Model中定义数据表对应的类。例如,数据表为Student,那么可以定义如下的类:
public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    // 其他属性
}
  1. 在Controller中定义更新当前行的方法和添加新记录的方法:
// 更新当前行
[HttpPost]
public ActionResult UpdateStudent(Student student)
{
    using (var db = new DbContext())
    {
        db.Entry(student).State = EntityState.Modified;
        db.SaveChanges();
    }
    return RedirectToAction("List");
}

// 添加新记录
[HttpPost]
public ActionResult AddStudent(Student student)
{
    using (var db = new DbContext())
    {
        db.Entry(student).State = EntityState.Added;
        db.SaveChanges();
    }
    return RedirectToAction("List");
}
  1. 在View中,可以通过表单提交来调用更新当前行的方法和添加新记录的方法:
@model Student
@using (Html.BeginForm("UpdateStudent", "Student", FormMethod.Post))
{
    @Html.HiddenFor(model => model.Id)
    @Html.TextBoxFor(model => model.Name)
    @Html.TextBoxFor(model => model.Age)

    
}
@using (Html.BeginForm("AddStudent", "Student", FormMethod.Post))
{
    @Html.TextBoxFor(model => model.Name)
    @Html.TextBoxFor(model => model.Age)

    
}

通过表单提交,可以将输入的数据封装成Student对象传递给Controller中的方法,从而更新当前行或者添加新记录。

相关内容

热门资讯

为切实保障!wepoker辅助... 为切实保障!wepoker辅助真的假的(透视)贪吃蛇辅助器2022(确实有辅助修改器)-哔哩哔哩一、...
值得注意的是!wepoker免... 值得注意的是!wepoker免费透视(透视)新上游辅助(好像有辅助工具)-哔哩哔哩1、首先打开新上游...
透视讲解!wepoker科技辅... 透视讲解!wepoker科技辅助器(透视)江西中至黑科技辅助软件(总是有辅助辅助器)-哔哩哔哩一、江...
透视中牌率!hhpoker德州... 透视中牌率!hhpoker德州透视挂(透视)潮汕激k脚本(果然是有辅助平台)-哔哩哔哩1、上手简单,...
透视好友房!竞技联盟透视插件(... 透视好友房!竞技联盟透视插件(透视)涂山山西辅助(本来真的有辅助辅助器)-哔哩哔哩1、涂山山西辅助透...
据了解!拱趴大菠萝十三水作必弊... 据了解!拱趴大菠萝十三水作必弊(透视)微信小程序辅助工具(其实是真的辅助软件)-哔哩哔哩1、用户打开...
透视讲解!约局吧德州有挂吗(透... 透视讲解!约局吧德州有挂吗(透视)多乐跑胡子辅助(一直是真的辅助平台)-哔哩哔哩1、让任何用户在无需...
透视脚本!wpk辅助(透视)7... 透视脚本!wpk辅助(透视)789大菠萝有挂吗(确实有辅助安装)-哔哩哔哩1、透视脚本!wpk辅助(...
透视挂!wepoker有透视功... 透视挂!wepoker有透视功能吗(透视)微信小程序微乐家乡辅助器(都是真的是有辅助软件)-哔哩哔哩...
近日!wepoker破解器有用... 近日!wepoker破解器有用吗(透视)福建天天开心辅助工具下载(果然有辅助下载)-哔哩哔哩1、完成...