MVC 4 使用 Bootstrap 编辑模态表单 [英] MVC 4 Edit modal form using Bootstrap

查看:27
本文介绍了MVC 4 使用 Bootstrap 编辑模态表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MVC 4 和实体框架来开发 Intranet Web 应用程序.我有一个可以通过编辑操作修改的人员列表.我想通过使用模态表单使我的应用程序更具动态性.所以我尝试将我的编辑视图放入我的 Bootstrap 模式中,我有 2 个关于它的问题:

  • 我应该使用简单视图还是局部视图?
  • 我如何执行验证(实际上它可以工作,但它会将我重定向到我的原始视图,所以不是在模态形式中)

我想我必须使用 AJAX 和/或 jQuery,但我不熟悉这些技术.任何帮助将不胜感激.

我的索引视图:

@model IEnumerable@{ViewBag.Title = "索引";}<h2>索引</h2><br/><div class="group"><input type="button" value="New person" class="btn" onclick="location.href='@Url.Action("Create")';return false;"/><input type="button" value="Download report" class="btn" onclick="location.href='@Url.Action("PersonReport")';return false;"/>

@using (Html.BeginForm("SelectedPersonDetails", "Person")){<form class="form-search"><input type="text" id="tbPerson" name="tbPerson" placeholder="查找员工..." class="input-medium search-query"><button type="submit" class="btn">搜索</button></表单>}<table class="table"><头><tr><th>名字</th><th>Lastname</th><th>开始日期</th><第>结束日期</th><th>详情</th><th>动作</th></tr></thead>@foreach(ViewBag.PageOfPersons 中的 BuSIMaterial.Models.Person 项目){<tr><td>@item.FirstName</td><td>@item.LastName</td><td>@item.StartDate.ToShortDateString()</td><td>@if (item.EndDate.HasValue){@item.EndDate.Value.ToShortDateString()}</td><td><a class="details_link" data-target-id="@item.Id_Person">详情</a></td><td><div><button class="btn btn-primary edit-person" data-id="@item.Id_Person">编辑</button>

</td></tr><tr><td colspan="6"><表格><tr><第>国民号码</th><td>@item.NumNat</td></tr><tr><th>车辆类别</th><td>@item.ProductPackageCategory.Name</td></tr><tr><th>升级</th><td>@item.Upgrade</td></tr><tr></th>上班的家</th><td>@item.HouseToWorkKilometers.ToString("G29")</td></tr><div id="details_@item.Id_Person"></div></td></tr>}</tbody><div class="modal hidefade in" id="edit-member"><div id="edit-person-container"></div>

@section 脚本{@Scripts.Render("~/bundles/jqueryui")@Styles.Render("~/Content/themes/base/css")<script type="text/javascript" language="javascript">$(document).ready(function () {$('#tbPerson').自动完成({来源:'@Url.Action("AutoComplete")'});$(".details_link").click(function () {var id = $(this).data("target-id");var url = '/ProductAllocation/ListByOwner/' + id;$("#details_"+ id).load(url);});$('.edit-person').click(function () {var url = "/Person/EditPerson";var id = $(this).attr('data-id');$.get(url + '/' + id, 函数(数据){$('#edit-person-container').html(data);$('.edit-person').modal('show');});});});}

我的部分视图:

@model BuSIMaterial.Models.Person<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h3 id="myModalLabel">编辑</h3>

<div>@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,新的 Ajax 选项{插入模式 = 插入模式.替换,HttpMethod = "POST",UpdateTargetId = "人员列表"})){@Html.ValidationSummary()@Html.AntiForgeryToken()<div class="modal-body"><div class="editor-field">@Html.TextBoxFor(model => model.FirstName, new { maxlength = 50 })@Html.ValidationMessageFor(model =>model.FirstName)

<div class="editor-field">@Html.TextBoxFor(model => model.LastName, new { maxlength = 50 })@Html.ValidationMessageFor(model =>model.LastName)

<div class="modal-footer"><button class="btn btn-inverse" type="submit">保存</button>

}

解决方案

你应该使用局部视图.我使用以下方法:

使用视图模型,这样您就不会将域模型传递给视图:

公共类 EditPersonViewModel{公共 int Id { 获取;放;}//这仅用于从 Db 中检索记录公共字符串名称 { 获取;放;}公共字符串年龄{得到;放;}}

在你的 PersonController:

[HttpGet]//此动作结果返回包含模态的部分公共 ActionResult EditPerson(int id){var viewModel = new EditPersonViewModel();viewModel.Id = id;return PartialView("_EditPersonPartial", viewModel);}[HttpPost]//此操作从模态中获取 viewModel公共 ActionResult EditPerson(EditPersonViewModel viewModel){如果(模型状态.IsValid){var toUpdate = personRepo.Find(viewModel.Id);toUpdate.Name = viewModel.Name;toUpdate.Age = viewModel.Age;personRepo.InsertOrUpdate(toUpdate);personRepo.Save();返回视图(索引");}}

接下来创建一个名为 _EditPersonPartial 的局部视图.这包含模态页眉、正文和页脚.它还包含 Ajax 表单.它是强类型的,并接受我们的视图模型.

@model Namespace.ViewModels.EditPersonViewModel<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h3 id="myModalLabel">编辑群组成员</h3>

<div>@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,新的 Ajax 选项{插入模式 = 插入模式.替换,HttpMethod = "POST",UpdateTargetId = "人员列表"})){@Html.ValidationSummary()@Html.AntiForgeryToken()<div class="modal-body">@Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Name)@Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Age)

<div class="modal-footer"><button class="btn btn-inverse" type="submit">保存</button>

}

现在在您的应用程序中的某个地方,说另一个部分 _peoplePartial.cshtml 等:

@foreach(模型中的var person.People){<button class="btn btn-primary edit-person" data-id="@person.PersonId">编辑</button>}

//这是模态定义<div class="modal hidefade in" id="edit-person"><div id="edit-person-container"></div>

<script type="text/javascript">$(document).ready(function () {$('.edit-person').click(function () {var url = "/Person/EditPerson";//控制器的urlvar id = $(this).attr('data-id');//列表中每个按钮的id$.get(url + '/' + id, 函数(数据){$('#edit-person-container').html(data);$('#edit-person').modal('show');});});});

I'm using MVC 4 and Entity Framework to develop an intranet web application. I have a list of persons which can be modify by an edit action. I wanted to make my app more dynamic by using modal forms. So I tried to put my edit view into my Bootstrap modal and I have 2 questions about it :

I think I have to use AJAX and/or jQuery but I'm new to these technologies. Any help would be appreciated.

EDIT : My Index View :

@model IEnumerable<BuSIMaterial.Models.Person>

@{
    ViewBag.Title = "Index";
}


<h2>Index</h2>

<br />

<div class="group">
        <input type="button" value="New person" class="btn" onclick="location.href='@Url.Action("Create")';return false;"/>
        <input type="button" value="Download report" class="btn" onclick="location.href='@Url.Action("PersonReport")';return false;"/>
</div>


@using (Html.BeginForm("SelectedPersonDetails", "Person"))
{  
    <form class="form-search">
        <input type="text" id="tbPerson" name="tbPerson" placeholder="Find an employee..." class="input-medium search-query">
        <button type="submit" class="btn">Search</button>
    </form>
}


<table class="table">
    <thead>
        <tr>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Start Date</th>
            <th>End Date</th>
            <th>Details</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
@foreach (BuSIMaterial.Models.Person item in ViewBag.PageOfPersons)
{
    <tr>
        <td>@item.FirstName</td>
        <td>@item.LastName</td>
        <td>@item.StartDate.ToShortDateString()</td>
        <td>
            @if (item.EndDate.HasValue)
            {
                @item.EndDate.Value.ToShortDateString()
            }        
        </td>

        <td>
            <a class="details_link" data-target-id="@item.Id_Person">Details</a>
        </td>

        <td>
            <div>
                <button class="btn btn-primary edit-person" data-id="@item.Id_Person">Edit</button>

            </div>
        </td>

    </tr>
    <tr>
        <td colspan="6">

            <table>
                <tr>
                    <th>National Number</th>
                    <td>@item.NumNat</td>
                </tr>
                <tr>
                    <th>Vehicle Category</th>
                    <td>@item.ProductPackageCategory.Name</td>
                </tr>
                <tr>
                    <th>Upgrade</th><td>@item.Upgrade</td>
                </tr>
                <tr>
                    <th>House to work</th>
                    <td>@item.HouseToWorkKilometers.ToString("G29")</td>
                </tr>
            </table>
            <div id="details_@item.Id_Person"></div>
        </td>

    </tr>

}
    </tbody>
</table>

<div class="modal hide fade in" id="edit-member">
    <div id="edit-person-container"></div>
</div>

@section Scripts
{
    @Scripts.Render("~/bundles/jqueryui")
    @Styles.Render("~/Content/themes/base/css")

    <script type="text/javascript" language="javascript">

        $(document).ready(function () {

            $('#tbPerson').autocomplete({
                source: '@Url.Action("AutoComplete")'
            });

            $(".details_link").click(function () {
                var id = $(this).data("target-id");
                var url = '/ProductAllocation/ListByOwner/' + id;
                $("#details_"+ id).load(url);
            });

            $('.edit-person').click(function () {
                var url = "/Person/EditPerson"; 
                var id = $(this).attr('data-id');
                $.get(url + '/' + id, function (data) {
                    $('#edit-person-container').html(data);
                    $('.edit-person').modal('show');
                });
            });


        });

    </script>
}

My Partial View :

@model BuSIMaterial.Models.Person

<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Edit</h3>
</div>
<div>

@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
                    new AjaxOptions
                    {
                        InsertionMode = InsertionMode.Replace,
                        HttpMethod = "POST",
                        UpdateTargetId = "list-of-people"
                    }))
{

    @Html.ValidationSummary()
    @Html.AntiForgeryToken()
    <div class="modal-body">
        <div class="editor-field">
            @Html.TextBoxFor(model => model.FirstName, new { maxlength = 50 })
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-field">
            @Html.TextBoxFor(model => model.LastName, new { maxlength = 50 })
            @Html.ValidationMessageFor(model => model.LastName)
        </div>
    </div>
    <div class="modal-footer">
        <button class="btn btn-inverse" type="submit">Save</button>
    </div>
}

解决方案

You should use partial views. I use the following approach:

Use a view model so you're not passing your domain models to your views:

public class EditPersonViewModel
{
    public int Id { get; set; }   // this is only used to retrieve record from Db
    public string Name { get; set; }
    public string Age { get; set; }
}

In your PersonController:

[HttpGet] // this action result returns the partial containing the modal
public ActionResult EditPerson(int id)
{  
    var viewModel = new EditPersonViewModel();
    viewModel.Id = id;
    return PartialView("_EditPersonPartial", viewModel);
}

[HttpPost] // this action takes the viewModel from the modal
public ActionResult EditPerson(EditPersonViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        var toUpdate = personRepo.Find(viewModel.Id);
        toUpdate.Name = viewModel.Name;
        toUpdate.Age = viewModel.Age;
        personRepo.InsertOrUpdate(toUpdate);
        personRepo.Save();
        return View("Index");
    }
}

Next create a partial view called _EditPersonPartial. This contains the modal header, body and footer. It also contains the Ajax form. It's strongly typed and takes in our view model.

@model Namespace.ViewModels.EditPersonViewModel
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Edit group member</h3>
</div>
<div>
@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
                    new AjaxOptions
                    {
                        InsertionMode = InsertionMode.Replace,
                        HttpMethod = "POST",
                        UpdateTargetId = "list-of-people"
                    }))
{
    @Html.ValidationSummary()
    @Html.AntiForgeryToken()
    <div class="modal-body">
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Name)
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Age)
    </div>
    <div class="modal-footer">
        <button class="btn btn-inverse" type="submit">Save</button>
    </div>
}

Now somewhere in your application, say another partial _peoplePartial.cshtml etc:

<div>
   @foreach(var person in Model.People)
    {
        <button class="btn btn-primary edit-person" data-id="@person.PersonId">Edit</button>
    }
</div>
// this is the modal definition
<div class="modal hide fade in" id="edit-person">
    <div id="edit-person-container"></div>
</div>

    <script type="text/javascript">
    $(document).ready(function () {
        $('.edit-person').click(function () {
            var url = "/Person/EditPerson"; // the url to the controller
            var id = $(this).attr('data-id'); // the id that's given to each button in the list
            $.get(url + '/' + id, function (data) {
                $('#edit-person-container').html(data);
                $('#edit-person').modal('show');
            });
        });
     });
   </script>

这篇关于MVC 4 使用 Bootstrap 编辑模态表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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