单击时 - 使 @Html.DisplayFor 成为可编辑的文本字段 [英] On Click - Make @Html.DisplayFor an editable text field

查看:26
本文介绍了单击时 - 使 @Html.DisplayFor 成为可编辑的文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在玩我制作的练习站点,我想尝试一种功能,该功能允许我选择表中的任何数据值,对其进行编辑,然后将其保存到数据库中.

现在我有一个编辑"在控制器中运行自动生成的 Edit 方法并有自己的视图用于编辑和保存的按钮,但我想在索引视图中尝试此编辑功能(或至少将数据传递给此索引视图中的编辑功能)

这是页面现在的样子

我还有一个行扩展脚本,用于显示一些我也希望可编辑的附加信息.(都在同一个视图中)

查看Index.cshtml

的代码

@model IEnumerable@{ViewBag.Title =索引";布局 = "~/Views/Shared/_Layout.cshtml";}<style type="text/css">表 tr 按钮 {不透明度:0.5;浮动:对;}表格tr:悬停按钮{不透明度:1;}</风格><br/><br/><br/><br/><div class="panel panel-primary";样式=宽度:100%"><div class="panel-heading"><span style="font-size: 30px;font-style:oblique"><span style="font-size:larger;"><span style="margin-right: 5px"class=glyphicon glyphicon-film"</span>电影</span></span>

<div class="col-lg-offset-8 col-lg-4"><按钮类型=按钮"样式=边距:3px";class =btn btn-success btn-block"onclick="location.href='@Url.Action("Create")';return false;"><span style="font-size:larger"><span style="右边距:5px"class=glyphicon glyphicon-plus"></span>添加新电影</span></button>

<table class="table table-striped table-hover table-responsive table-condensed"><tr><th><h4 style="font-size:x-large"><span style="font-weight:bolder">Title</span></h4></th><th><h4 style="font-size:x-large"><span style="font-weight:bolder">发布日期</span></h4></th><th><h4 style="font-size:x-large"><span style="font-weight:bolder">@Html.DisplayNameFor(model => model.Description)</span></th><th>@using (Html.BeginForm("Index", "Movie")){<div class="dropdown"><select class="btn btn-group-lg btn-default col-lg-4";style="margin-top: 15px;高度:36px;不透明度:1"数据切换=下拉"名称=过滤器"><选项值=0"禁用选择>过滤依据...</option><option value=1">电影名称</option><选项值=2">描述</option></选择>

<输入类型=文本"名称=搜索字符串"类=col-lg-6";style="margin-top: 16px;文字对齐:居中;高度:35px;字体大小:20px"占位符=输入文本"/><按钮类型=提交"class =btn btn-group-lg btn-primary col-lg-2 glyphicon glyphicon-arrow-right";style="margin-top: 15px;高度:36px;不透明度:1"值="/>}</th></tr>@foreach(模型中的变量项目){<tr><td class=col-lg-2"><span style="font-size: 17px;">@Html.DisplayFor(modelItem => item.Name)</span></td><td class=col-lg-3"><span style="font-size: 17px;">@Html.DisplayFor(modelItem => item.ReleaseDate)</span></td><td class=col-lg-3"><span style="font-size: 17px;font-style:italic">@Html.DisplayFor(modelItem => item.Description)</span></td><td class=col-lg-3 col-lg-offset-1"><按钮类型=按钮"class="btn btn-warning col-lg-4";onclick="location.href='@Url.Action(Edit", Movie", new { id = item.ID })';return false;"><span style="margin-右:5px"class=glyphicon glyphicon-pencil"></span>编辑</button><按钮类型=按钮"class="btn btn-danger col-lg-4 col-lg-offset-4";onclick="location.href='@Url.Action("Delete", "Movie", new { id = item.ID })' ;return false;"><span style="margin-右:5px"class=glyphicon glyphicon-trash"></span>删除</button></td></tr><tr><td colspan=12"><p style="font-size: 17px;字体样式:斜体;font-family: 'Roboto', sans-serif>电影 ID:@Html.DisplayFor(modelItem => item.ID)<br/>占位符</p></td></tr>}<span style="font-style: italic;字体大小:15px;字体系列:'Roboto',无衬线;填充顶部:0px"/>点击查看详情</span>

<脚本>$(函数(){$("td[colspan=12]").find("p").hide();$("td[colspan=12]").addClass("nopadding");$("tr").click(function () {var $target = $(this);var $detailsTd = $target.find("td[colspan=12]");如果($detailsTd.length){$detailsTd.find(p").slideUp();$detailsTd.addClass("nopadding");} 别的 {$detailsTd = $target.next().find("td[colspan=12]");$detailsTd.find(p").slideToggle();$detailsTd.toggleClass(nopadding");}});});@Scripts.Render("~/bundles/myscript")

电影

的控制器代码

命名空间 WebApplication2.Controllers{公共类 MovieController : 控制器{私人电影实体数据库 = 新电影实体();//获取:/电影/公共动作结果索引(字符串过滤器,字符串搜索字符串){if (String.IsNullOrEmpty(searchString) || (Int32.Parse(Filter) == 0)){返回视图(db.Movies.ToList());}别的{var 参数 = Int32.Parse(Filter);return View(db.Movies.Where(x => (parameter == 1 && x.Name.Contains(searchString)) || (parameter == 2 && x.Description.Contains(searchString))).Distinct().ToList().OrderBy(x => x.Name));}}//获取:/电影/详细信息/5公共操作结果详细信息(int?id){如果(id == null){返回新的 HttpStatusCodeResult(HttpStatusCode.BadRequest);}电影电影 = db.Movies.Find(id);如果(电影 == 空){返回 HttpNotFound();}返回视图(电影);}//获取:/电影/创建公共 ActionResult 创建(){返回视图();}//发布:/电影/创建//为了防止过度发布攻击,请启用您要绑定的特定属性,例如//更多详细信息,请参见 http://go.microsoft.com/fwlink/?LinkId=317598.[HttpPost][验证AntiForgeryToken]public ActionResult Create([Bind(Include = "ID,Name,ReleaseDate,Description")] 电影电影){如果(模型状态.IsValid){db.Movies.Add(电影);db.SaveChanges();返回 RedirectToAction(索引");}返回视图(电影);}//获取:/电影/编辑/5公共操作结果编辑(int?id){如果(id == null){返回新的 HttpStatusCodeResult(HttpStatusCode.BadRequest);}电影电影 = db.Movies.Find(id);如果(电影 == 空){返回 HttpNotFound();}返回视图(电影);}//发布:/电影/编辑/5//为了防止过度发布攻击,请启用您要绑定的特定属性,例如//更多详细信息,请参见 http://go.microsoft.com/fwlink/?LinkId=317598.[HttpPost][验证AntiForgeryToken]public ActionResult Edit([Bind(Include = "ID,Name,ReleaseDate,Description")] 电影电影){如果(模型状态.IsValid){db.Entry(movie).State = EntityState.Modified;db.SaveChanges();返回 RedirectToAction(索引");}返回视图(电影);}//获取:/电影/删除/5公共 ActionResult 删除(int?id){如果(id == null){返回新的 HttpStatusCodeResult(HttpStatusCode.BadRequest);}电影电影 = db.Movies.Find(id);如果(电影 == 空){返回 HttpNotFound();}返回视图(电影);}//发布:/电影/删除/5[HttpPost, ActionName(删除")][验证AntiForgeryToken]公共 ActionResult DeleteConfirmed(int id){电影电影 = db.Movies.Find(id);db.Movies.Remove(电影);db.SaveChanges();返回 RedirectToAction(索引");}受保护的覆盖无效处置(布尔处置){如果(处置){db.Dispose();}base.Dispose(处置);}}}

是的,所以通常我点击编辑"按钮,我转到一个新视图,然后进行更改并将其保存到数据库中.但我想通过点击数据本身(@Html.DisplayFor(modelItem => item.INSERT_ITEM_NAME): Title, Release Date, Description, MovieID,占位符)并将相应的选项转换为文本字段以供编辑.

参考:我也会有一个保存"按钮在这段时间内出现,以实际保存将替换编辑"和删除"的更改,直到编辑完成.

我再次不确定这是否完全可能,但任何和所有帮助都将不胜感激!

解决方案

在你的 Razor 模板中,你需要一个 @Html.DisplayFor(...) 和一个 @Html.EditorFor(...).文本字段应该是隐藏的,点击显示文本后,JavaScript需要隐藏显示文本并显示文本字段,然后设置焦点:

@Html.DisplayFor(modelItem => modelItem.Description)</span><span class="item-field">@Html.EditorFor(modelItem => modelItem.Description)</span>

一些 CSS:

.item-field: {显示:无;}

还有一些很好的 jQuery:

$(document.documentElement).on("click", "span.item-display", function(event) {$(event.currentTarget).隐藏().next("span.item-field").展示().find(":输入:第一个").重点().选择();}).on("keypress", "span.item-field", function(event) {if (event.keyCode != 13)返回;event.preventDefault();var $field = $(event.currentTarget),$display = $field.prev("span.item-display");$display.html($field.find(":input:first").val());$display.show();$field.hide();});

JSFiddle:http://jsfiddle.net/A3bg6/1/

在文本字段上按 ENTER 时,它将隐藏字段并显示显示,并更新显示.

So I am playing with a practice site I made and I want to attempt a feature that will allow me to select any data value in the table, edit it, then save it to the Database.

Right now I have an "Edit" button that runs an auto-generated Edit method in the controller and that has its own View for editing and saving, but I want to attempt this edit function within the Index View (or at least pass the data to the edit function within this Index view)

Here is how the page looks right now

I also have a row-expand script that display some additional information that I also want to be editable. (all in same view)

View Code for Index.cshtml

@model IEnumerable<WebApplication2.Entities.Movie>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<style type="text/css">
    table tr button {
        opacity: 0.5;
        float: right;
    }

    table tr:hover button {
        opacity: 1;
    }
</style>

<br />
<br />
<br />
<br />
<div class="panel panel-primary" style="width:100%">
    <div class="panel-heading">
        <span style="font-size: 30px; font-style:oblique"><span style="font-size:larger;"><span style="margin-right: 5px" class="glyphicon glyphicon-film"></span>Movies</span></span>
    </div>

    <div class="col-lg-offset-8 col-lg-4">
        <button type="button" style="margin:3px" class="btn btn-success btn-block" onclick="location.href='@Url.Action("Create")';return false;"><span style="font-size:larger"><span style="margin-right: 5px" class="glyphicon glyphicon-plus"></span>Add New Movie</span></button>

    </div>

    <table class="table table-striped table-hover table-responsive table-condensed">
        <tr>
            <th>
                <h4 style="font-size:x-large"><span style="font-weight:bolder">Title</span></h4>
            </th>
            <th>
                <h4 style="font-size:x-large"><span style="font-weight:bolder">Release Date</span></h4>
            </th>
            <th>
                <h4 style="font-size:x-large"><span style="font-weight:bolder">@Html.DisplayNameFor(model => model.Description)</span></h4>
            </th>
            <th>
                @using (Html.BeginForm("Index", "Movie"))
                {
                    <div class="dropdown">
                        <select class="btn btn-group-lg btn-default col-lg-4" style="margin-top: 15px; height: 36px; opacity: 1" data-toggle="dropdown" name="Filter">
                            <option value="0" disabled selected>Filter By...</option>
                            <option value="1">Movie Name</option>
                            <option value="2">Description</option>
                        </select>
                    </div>

                    <input type="text" name="searchString" class="col-lg-6" style="margin-top: 16px; text-align:center; height:35px; font-size:20px" placeholder="enter text" />
                    <button type="submit" class="btn btn-group-lg btn-primary col-lg-2 glyphicon glyphicon-arrow-right" style="margin-top: 15px; height:36px; opacity:1" value="" />
                }
            </th>
        </tr>

        @foreach (var item in Model)
        {
            <tr>
                <td class="col-lg-2">
                    <span style="font-size: 17px;">@Html.DisplayFor(modelItem => item.Name)</span>
                </td>
                <td class="col-lg-3">
                    <span style="font-size: 17px;">@Html.DisplayFor(modelItem => item.ReleaseDate)</span>
                </td>
                <td class="col-lg-3">
                    <span style="font-size: 17px; font-style:italic">@Html.DisplayFor(modelItem => item.Description)</span>
                </td>
                <td class="col-lg-3 col-lg-offset-1">
                    <button type="button" class="btn btn-warning col-lg-4" onclick="location.href='@Url.Action("Edit", "Movie", new { id = item.ID })';return false;"><span style="margin-right: 5px" class="glyphicon glyphicon-pencil"></span>Edit</button>
                    <button type="button" class="btn btn-danger col-lg-4 col-lg-offset-4" onclick="location.href='@Url.Action("Delete", "Movie", new { id = item.ID })' ;return false;"><span style="margin-right: 5px" class="glyphicon glyphicon-trash"></span>Delete</button>
                </td>
            </tr>
            <tr>
                <td colspan="12">
                    <p style="font-size: 17px; font-style: italic; font-family: 'Roboto', sans-serif">
                        Movie ID: @Html.DisplayFor(modelItem => item.ID)
                        <br />
                        Placeholder
                    </p>
                </td>
            </tr>
        }
    </table>
    <span style="font-style: italic; font-size: 15px; font-family: 'Roboto', sans-serif; padding-top:0px" />click for details</span>
</div>

<script>

    $(function () {
        $("td[colspan=12]").find("p").hide();
        $("td[colspan=12]").addClass("nopadding");

        $("tr").click(function () {
            var $target = $(this);
            var $detailsTd = $target.find("td[colspan=12]");
            if ($detailsTd.length) {
                $detailsTd.find("p").slideUp();
                $detailsTd.addClass("nopadding");
            } else {
                $detailsTd = $target.next().find("td[colspan=12]");
                $detailsTd.find("p").slideToggle();
                $detailsTd.toggleClass("nopadding");
            }
        });
    });

</script>
@Scripts.Render("~/bundles/myscript")

Controller code for Movie

namespace WebApplication2.Controllers
{
    public class MovieController : Controller
    {
        private MoviesEntities db = new MoviesEntities();

        // GET: /Movie/
        public ActionResult Index(string Filter, string searchString)
        {

            if (String.IsNullOrEmpty(searchString) || (Int32.Parse(Filter) == 0))
            {
                return View(db.Movies.ToList());
            }
            else
            {
                var parameter = Int32.Parse(Filter);
                return View(db.Movies.Where(x => (parameter == 1 && x.Name.Contains(searchString)) || (parameter == 2 && x.Description.Contains(searchString))).Distinct().ToList().OrderBy(x => x.Name));
            }

        }

        // GET: /Movie/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Movie movie = db.Movies.Find(id);
            if (movie == null)
            {
                return HttpNotFound();
            }
            return View(movie);
        }

        // GET: /Movie/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /Movie/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ID,Name,ReleaseDate,Description")] Movie movie)
        {
            if (ModelState.IsValid)
            {
                db.Movies.Add(movie);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(movie);
        }

        // GET: /Movie/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Movie movie = db.Movies.Find(id);
            if (movie == null)
            {
                return HttpNotFound();
            }
            return View(movie);
        }

        // POST: /Movie/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID,Name,ReleaseDate,Description")] Movie movie)
        {
            if (ModelState.IsValid)
            {
                db.Entry(movie).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(movie);
        }

        // GET: /Movie/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Movie movie = db.Movies.Find(id);
            if (movie == null)
            {
                return HttpNotFound();
            }
            return View(movie);
        }

        // POST: /Movie/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Movie movie = db.Movies.Find(id);
            db.Movies.Remove(movie);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

Yea so generally I click the "Edit" button, I go to a new View and then I make changes and save it to the DB. But I would like to do that all within the Index View by just clicking on the data itself (@Html.DisplayFor(modelItem => item.INSERT_ITEM_NAME): Title, Release Date, Description, MovieID, Placeholder) and turn the respective option into a text field for editing.

Reference: I would also have a "Save" button appear during this time to actually save the changes that would replace the Edit and Delete until the editing finished.

Again I am not sure if this is entirely possible, but any and all help would be greatly appreciated!

解决方案

In your Razor template, you will need both an @Html.DisplayFor(...) and an @Html.EditorFor(...). The text field should be hidden, and upon clicking the display text, JavaScript needs to hide the display text and show the text field, then set focus to it:

<span class="item-display">
    @Html.DisplayFor(modelItem => modelItem.Description)
</span>
<span class="item-field">
    @Html.EditorFor(modelItem => modelItem.Description)
</span>

Some CSS:

.item-field: {
    display: none;
}

And some jQuery for good measure:

$(document.documentElement)
    .on("click", "span.item-display", function(event) {
        $(event.currentTarget)
            .hide()
            .next("span.item-field")
            .show()
            .find(":input:first")
            .focus()
            .select();
    })
    .on("keypress", "span.item-field", function(event) {
        if (event.keyCode != 13)
            return;

        event.preventDefault();

        var $field = $(event.currentTarget),
            $display = $field.prev("span.item-display");

        $display.html($field.find(":input:first").val());
        $display.show();
        $field.hide();
    });

JSFiddle: http://jsfiddle.net/A3bg6/1/

When pressing ENTER on the text field, it will hide the field and show the display, plus update the display.

这篇关于单击时 - 使 @Html.DisplayFor 成为可编辑的文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆