当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET Mvc开发之删除修改数据

ASP.NET Mvc开发之删除修改数据

2017年12月12日  | 移动技术网IT编程  | 我要评论

爱情公寓闪电侠,新妹魔王的契约者第二季,中国换客网

之前那篇文章介绍了asp.net mvc使用ef来查询数据和ef中dbquery<t>泛型对象对数据的延迟加载。今天我们就来看看我们怎么使用ef来删除数据。

其实现在的web开发通用的模式就是前端使用js和jquery来和后端进行数据交互。那么我们就在前端来加两个删除和更新的脚本。代码如下:

       <!--遍历 action方法 设置给 viewdata 的集合数据,生成html代码-->
      @foreach (blogarticle a in viewdata["datalist"] as list<blogarticle>)
      {
        <tr>
          <td>@a.aid</td>
          <td>@a.atitle</td>
          <td>@a.blogarticlecate.name</td>
          <td>@a.enumeration.e_cname</td>
          <td>@a.aaddtime</td>
          <!---------为文章列表添加删除按钮--------->>
          <td><a href="javascript:del(@a.aid)">删除</a></td>

        </tr>
      }

然后为该按钮编写js脚本函数,代码如下:

<script type="text/javascript">
    function del(id) {
      if (confirm("确定要删除么?")) {

          <!--这里配置当用户确定删除时,js让页面跳转到的的url地址-->
        window.location="/home/del/"+ id;
      }
    }
  </script>

上面的js代码的意思是,当用户点击删除按钮时,url跳转的地址是"/home/del"+id

 点击前的效果如下图,注意url地址是

它代表的意思是,浏览器现根据路由,请求了控制器(controller),控制器根据路由的配置, 返回视图方法,然后试图再把html,js等回传给浏览器。

点击删除按钮并确定,注意url地址是

说明我们配置的路由信息是“home/del”

所以我们在控制器的homecontroller中添加一个del方法,来完成删除操作,代码如下:

首先我们先来看看mvc默认的路由表配置,在app_start文件夹下的routeconfig.cs,代码如下:

//路由表配置
  public class routeconfig
  {
    
    public static void registerroutes(routecollection routes)
    {
      routes.ignoreroute("{resource}.axd/{*pathinfo}");

      routes.maproute(
        name: "default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "home", action = "index", id = urlparameter.optional }
      );
    }
  }
 

我们可以发现ur的默认配置模式是"{controller}/{action}/{id}"

默认的配置信息是defaults: new { controller = "home", action = "index", id = urlparameter.optional }

特别注意的是id = urlparameter.optional是可选的。

所以我们应该在homecontroller.cs中创建一个del类型的action方法,代码如下:

 //删除文章
    public actionresult del(int id)
    {
      //操作数据库使用try...catch来捕捉异常
      try
      {
        //创建删除对象
        blogarticle artticle = new blogarticle();
        artticle.aid = id;
        //将删除对象添加到ef 对象管理容器
        db.blogarticles.attach(artticle);
        //将对象包装类的状态标识为删除状态
        db.blogarticles.remove(artticle);
        //更新到数据库
        db.savechanges();
        //更新成功后,页面跳转到index页面
        return redirecttoaction("index", "home");
      }
      catch (exception ex)
      {
        return redirecttoaction("友好页面");
      }
      //return view();
    }

这样就完成了数据的删除操作。

接下来我们就来完成修改的代码,我们先展示视图(view)代码如下

 <!--生成一个表单,并且指明表单提交方法,和路由-->
  @using (html.beginform("modify", "home", formmethod.post))
  { 
    <table id="tblist">
      <tr>
        <td colspan="2">修改 @html.hiddenfor(a=>a.aid) </td>
      </tr>
      <tr>
        <td>标题:</td>
        @*<td>@html.textbox("txtname",(object)model.atitle)</td>*@

        <!--使用htmlhelper的强类型方法 直接 从 model 中 根据 atitle 属性生成文本框-->
        <td>@html.textboxfor(a=>a.atitle)</td>
      </tr>
      <tr>
        <td>分类:</td>
        <!--使用强类型方法生成下拉框,并自动根据 model属性里的acate值 设置 下拉框的默认选中项-->
        <td>@html.dropdownlistfor(a=>a.acate,viewbag.catelist as ienumerable<selectlistitem>)</td>
      </tr>
      <tr>
        <td>内容:</td>
        <!--使用htmlhelper的强类型方法 直接 从 model 中 根据 acontent 属性生成文本域-->
        <td>@html.textareafor(a => a.acontent, 10, 60, null)</td>
      </tr>
      <tr>
        <td colspan="2"><input type="submit" value="确定修改" /> @html.actionlink("返回","index","home")</td>
      </tr>
    </table>
  }

我们的后端代码改如何编写呢?

//因为我们这个action是在表达以post方式提交时执行的,所以加上标识
    [httpget]
    /// <summary>
    /// 加载需要修改文章
    /// </summary>
    /// <param name="id">需要修改文章的id</param>
    /// <returns></returns>
    public actionresult editarticle(int id)
    {
      //获取需要编辑文章,并且返回该实体对象的第一个元素
      blogarticle art = (from c in db.blogarticles where c.aid == id select c).firstordefault();
      
      //我们把文章的分类做成一个下拉列表,并且给droplist的<option>赋值
      ienumerable<selectlistitem> selelistitem = (from a in db.blogarticlecates where a.isdel == false select a).tolist().select(a => new selectlistitem { value = a.id.tostring(), text = a.name });

      //返回list对象
      viewbag.catelist = selelistitem;

      return view();
    }
接下来就是执行修改的代码:
[httppost]
    /// <summary>
    /// 执行修改的代码
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public actionresult modify(blogarticle model)
    {
      try
      {
        //1.将实体对象 a.加入 ef 对象容器中,并 b.获取 伪包装类对象
        dbentityentry<blogarticle> entry = db.entry<blogarticle>(model);
        //2.将包装类对象的状态设置为 unchanged
        entry.state = system.data.entitystate.unchanged;
        //3.设置 被改变的属性
        entry.property(a => a.atitle).ismodified = true;
        entry.property(a => a.acontent).ismodified = true;
        entry.property(a => a.acate).ismodified = true;

        //4.提交到数据库 完成修改
        db.savechanges();
        //5.更新成功,则命令浏览器 重定向 到 /home/list 方法
        return redirecttoaction("index", "home");
      }
      catch (exception ex)
      {
        return content("修改失败~~~" + ex.message);
      }
    } 

到此我们就完成了使用mvc建立一个小站点的任务,而且也完成了对数据的增删改查的操作。

希望本文所述对大家学习有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网