• MVC中CRUD


    今天看见页面操作中方法重载,里面提到过一点,Action处理的思路是:“从哪来回到哪里去”。

    看下面代码截图

     1         public ActionResult Delete(int id)
     2         {
     3             ViewData.Model = dbContext.ClassInfos.Find(id);
     4             return View();
     5         }
     6 
     7         [HttpPost]
     8         public ActionResult Delete(int id, FormCollection collection)
     9         {
    10            //删除数据
    11             ClassInfos classInfos=new ClassInfos();
    12             classInfos.ClassInfoName = string.Empty;
    13             classInfos.Id = id;
    14             dbContext.ClassInfos.Attach(classInfos);
    15             dbContext.Entry(classInfos).State=EntityState.Deleted;
    16             dbContext.SaveChanges();
    17 
    18             return RedirectToAction("Index");
    19         }

    然后对应的view页面

     1 <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcModel.ClassInfos>" %>
     2 
     3 <!DOCTYPE html>
     4 
     5 <html>
     6 <head runat="server">
     7     <meta name="viewport" content="width=device-width" />
     8     <title>Delete</title>
     9 </head>
    10 <body>
    11     <h3>Are you sure you want to delete this?</h3>
    12     <fieldset>
    13         <legend>ClassInfos</legend>
    14     
    15         <div class="display-label">
    16             <%: Html.DisplayNameFor(model => model.ClassInfoName) %>
    17         </div>
    18         <div class="display-field">
    19             <%: Html.DisplayFor(model => model.ClassInfoName) %>
    20         </div>
    21     </fieldset>
    22     <% using (Html.BeginForm()) { %>
    23         <p>
    24             <input type="submit" value="Delete" /> |
    25             <%: Html.ActionLink("Back to List", "Index") %>
    26         </p>
    27     <% } %>
    28     
    29 </body>
    30 </html>

    其中主界面如下:即实现删除一行数据的功能,点击Delete,然后跳转对应的方法,实现删除功能。

    点击Delete后弹出下面界面

    通过审查网页元素和网页源代码对比(左边为源代码,右边为审查元素代码)

    有没有发现,虽然左边的<% using(html.BeginForm()){...}%>没有将action写明,但是生成的网页中会自动填充action为 右边图中的 action="/ClassInfo/Delete/0" method="post"

    默认情况下,form都已post方式提交请求。

    这样就实现了“从哪里来回到哪里去”的思想

    解释:点击删除提交的方法(Action)是 Delete(int id) 对应的代码url为:http://localhost:1794/Classinfos/Delete/0

    页面跳转到 删除界面,即需要点击删除按钮“delete”时,提交的action同样为Delete方法,不过已Post提交,Controller中实现的方法为Delete(int id,FormCollection collection)方法,

    Url为 “/ClassInfos/Delete/0” 。

    上面知识个人的一点小见解,功能实现的一点心得,或许没能理解其中的原理,但是对于初学者来说,明白转化过程还是十分重要的。

  • 相关阅读:
    找出字符串中最长的对称字符串
    spark 数据倾斜的一些表现
    executor.Executor: Managed memory leak detected; size = 37247642 bytes, TID = 5
    机器学习复习笔记
    博客园如何在侧边添加目录
    markdown画图
    用hexo搭建博客
    苏州大学2005-2019复试上机真题及保研期中期末习题
    考研复试面试:计算机网络面试题整理
    python进行日期计算
  • 原文地址:https://www.cnblogs.com/zhaosw/p/5234677.html
Copyright © 2020-2023  润新知