你的位置:首页 > ASP.net教程

[ASP.net教程]mvc JQuery 修改


Models文件夹里面可以Linq,Entity两种映射框架,也允许有ADO的操作,甚至可以ADO代码和映射代码一起操作

控制器当中允许有相同的方法名,类似在做修改时有两个Modify方法,但是MVC中没有视为合法的重载,要用不同的请求方式来区分,也就是要用特性HttpPost和HttpGet来区分两个方法


在修改页面的视图上,每个表单元素都要有name属性,而且属性值要和实体属性名一致

在控制器方法中获取视图上的表单元素值有3种方法:
1、实体自动映射,只要表单元素的name名称与实体属性名相同
2、request.Form["name名称"]
3、FormCollection,它是视图页面上表单元素的集合

控制器向视图传值的几种方式:
1、通过控制器的返回值View(参数),视图页面用Model接收传值
2、也可以在控制器中用ViewBag.属性名,视图页面上也用ViewBag.属性名接收

 

 [HttpGet] //获取数据
        public ActionResult Modify(int id)
        {
            Books mod=db.Books.Where(b => b.Id == id).FirstOrDefault();
            if (mod != null)
            {
                ViewBag.data = db.Publishers.ToList();
                return View(mod);
            }
            return Content("not found");
        }

        [HttpPost]//修改
        public ActionResult Modify(FormCollection fc)
        {
            //string title = fc["title"];
            string title = Request.Form["title"];
            //Books book=db.Books.Where(b => b.Id == mod.Id).FirstOrDefault();
            //book.Title = mod.Title;
            //book.UnitPirce=....
            //db.SaveChanges();
            return Redirect("/Book/Index");
        }

 

 <div>
        <table>
            @foreach (var item in Model as List<Books>)
            {
                <tr>
                    <td>@item.Title</td>
                    <td><a href="http://www.cnblogs.com//Book/Delete/@item.Id">删除</a></td>
                    <td><a href="http://www.cnblogs.com//Book/Modify/@item.Id">修改</a></td>
                </tr>
            }
        </table>
    </div>

 

@model MvcApplication2.Models.Books
@using MvcApplication2.Models    

  <form action="/Book/Modify" method="post">    //Modify.cshtml
        <input type="hidden" name="Id" value="@Model.Id" />
        <table>
            <tr>
                <td>标题:</td>
                <td><input name="Title" id="Title" value="@Model.Title" type="text" /></td>
            </tr>
            <tr>
                <td>出版社:</td>
                <td>
                    <select name="PublisherId">
                        @foreach (var item in ViewBag.data as List<Publishers>)
                        {
                            if(item.pid==Model.PublisherId){
                              <option value="@item.pid" selected>@item.pubName</option>
                            }
                            else
                            {
                                <option value="@item.pid">@item.pubName</option>
                            }
                        }
                    </select>
                </td>
            </tr>
            <tr>
                <td></td>
                <td><input id="Submit1" type="submit" value="确定" /></td>
            </tr>
        </table>
    </form>