使用引导MVC 4编辑模式窗体 [英] MVC 4 Edit modal form using Bootstrap

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

问题描述

我使用MVC 4和实体框架,开发一个内部网的Web应用程序。我可以通过编辑动作来改变人的名单。我想让使用模式窗体我的应用程序更有活力。于是,我把我的编辑视图到我的引导模式,我对此有2个问题:

  • 我应该使用一个简单的或部分的看法?
  • 如何执行验证(实际上它的工作,但它重定向我到我原来的视图,以便不会在模式窗体)

我觉得我必须使用AJAX和/或jQuery的,但我是新来的这些技术。任何帮助将是AP preciated。

编辑:我的索引视图:

  @model IEnumerable的< BuSIMaterial.Models.Person>

@ {
    ViewBag.Title =指数;
}


< H2>指数< / H>

< BR />

< D​​IV CLASS =组>
        <输入类型=按钮值=新人级=BTN的onclick =location.href ='@ Url.Action(创建);返回false;/>
        <输入类型=按钮值=下载报告级=BTN的onclick =location.href ='@ Url.Action(PersonReport)';返回false;/>
< / DIV>


@using(Html.BeginForm(SelectedPersonDetails,人))
{
    <窗​​体类=形搜索>
        <输入类型=文本ID =tbPersonNAME =tbPerson占位符=查找员工......级=输入中的搜索查询>
        <按钮类型=提交级=BTN>搜索< /按钮>
    < /形式GT;
}


<表类=表>
    < THEAD>
        &其中; TR>
            百分位>名字< /第i个
            <第i个姓氏< /第i个
            百分位>开始日期和LT; /第i个
            <第i个结束日期< /第i个
            百分位>详情< /第i个
            百分位>操​​作< /第i个
        < / TR>
    < / THEAD>
    < TBODY>
@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>
            &其中;一类=details_link数据目标的id =@ item.Id_Person>详情&所述; / a取代;
        < / TD>

        < TD>
            < D​​IV>
                <按钮类=BTN BTN-主要编辑人数据ID =@ item.Id_Person>编辑< /按钮>

            < / DIV>
        < / TD>

    < / TR>
    &其中; TR>
        < TD合并单元格=6>

            <表>
                &其中; TR>
                    <第i个国家数目和LT; /第i个
                    < TD> @ item.NumNat< / TD>
                < / TR>
                &其中; TR>
                    <第i个车辆类别< /第i个
                    < TD> @ item.ProductPackageCategory.Name< / TD>
                < / TR>
                &其中; TR>
                    百分位>升级< /第i;< TD> @ item.Upgrade< / TD>
                < / TR>
                &其中; TR>
                    <第i个府的工作和LT; /第i个
                    < TD> @ item.HouseToWorkKilometers.ToString(G29)< / TD>
                < / TR>
            < /表>
            < D​​IV ID =details_@item.Id_Person>< / DIV>
        < / TD>

    < / TR>

}
    < / TBODY>
< /表>

< D​​IV CLASS = ID =编辑组成的&GT模式隐藏在变脸;
    < D​​IV ID =编辑人集装箱>< / DIV>
< / DIV>

@section脚本
{
    @ Scripts.Render(〜/包/ jQueryUI的)
    @ Styles.Render(〜/内容/主题/基/ CSS)

    <脚本类型=文/ JavaScript的LANGUAGE =JavaScript的>

        $(文件)。就绪(函数(){

            $('#tbPerson)。自动完成({
                来源:@ Url.Action(自动完成)
            });

            $(details_link)。点击(函数(){
                VAR ID = $(本)的.d​​ata(目标ID);
                VAR URL ='/ ProductAllocation / ListByOwner /+ ID;
                $(#细节_+编号).load(URL);
            });

            $('。编辑人)。点击(函数(){
                VAR URL =/人/ EditPerson;
                VAR ID = $(本).attr(数据ID);
                $获得(网址+/+ ID,功能(数据){
                    $('#编辑人集装箱)HTML(数据)。
                    $(编辑人。)模式('秀')。
                });
            });


        });

    < / SCRIPT>
}
 

我的部分观点:

  @model BuSIMaterial.Models.Person

< D​​IV CLASS =模式的首部>
<按钮式=按钮级=关闭数据解雇=莫代尔ARIA隐藏=真>×< /按钮>
    < H3 ID =myModalLabel>编辑< / H3>
< / DIV>
< D​​IV>

@using(Ajax.BeginForm(EditPerson,人,FormMethod.Post,
                    新AjaxOptions
                    {
                        InsertionMode = InsertionMode.Replace,
                        HttpMethod =POST
                        以人列表中,UpdateTargetId =
                    }))
{

    @ Html.ValidationSummary()
    @ Html.AntiForgeryToken()
    < D​​IV CLASS =模态体>
        < D​​IV CLASS =主编场>
            @ Html.TextBoxFor(型号=> model.FirstName,新{最大长度= 50})
            @ Html.ValidationMessageFor(型号=> model.FirstName)
        < / DIV>

        < D​​IV CLASS =主编场>
            @ Html.TextBoxFor(型号=> model.LastName,新{最大长度= 50})
            @ Html.ValidationMessageFor(型号=> model.LastName)
        < / DIV>
    < / DIV>
    < D​​IV CLASS =模式躯>
        <按钮类=BTN BTN-反类型=提交>保存< /按钮>
    < / DIV>
}
 

解决方案

您应该使用局部视图。我用下面的方法:

使用视图模型让你不通过你的域模型,以你的观点:

 公共类EditPersonViewModel
{
    公众诠释编号{获得;组; } //这只是用来从数据库中检索记录
    公共字符串名称{;组; }
    公共字符串年龄{获得;组; }
}
 

在你的 PersonController:

  [HTTPGET] //此操作的结果返回部分含有莫代尔
公众的ActionResult EditPerson(INT ID)
{
    VAR视图模型=新EditPersonViewModel();
    viewModel.Id = ID;
    返回PartialView(_ EditPersonPartial,视图模型);
}

[HttpPost] //这个动作发生的视图模型的模态
公众的ActionResult EditPerson(EditPersonViewModel视图模型)
{
    如果(ModelState.IsValid)
    {
        VAR更新所使用= personRepo.Find(viewModel.Id)​​;
        toUpdate.Name = viewModel.Name;
        toUpdate.Age = viewModel.Age;
        personRepo.InsertOrUpdate(更新所使用);
        personRepo.Save();
        返回查看(「指数」);
    }
}
 

接下来创建一个名为局部视图 _EditPersonPartial 。这包含了模式的标题,正文和页脚。它还包含了Ajax的形式。它是强类型,并采取在我们的视图模型。

  @model Namespace.ViewModels.EditPersonViewModel
< D​​IV CLASS =模式的首部>
<按钮式=按钮级=关闭数据解雇=莫代尔ARIA隐藏=真>×< /按钮>
    < H3 ID =myModalLabel>编辑组成员LT; / H3>
< / DIV>
< D​​IV>
@using(Ajax.BeginForm(EditPerson,人,FormMethod.Post,
                    新AjaxOptions
                    {
                        InsertionMode = InsertionMode.Replace,
                        HttpMethod =POST
                        以人列表中,UpdateTargetId =
                    }))
{
    @ Html.ValidationSummary()
    @ Html.AntiForgeryToken()
    < D​​IV CLASS =模态体>
        @ Html.Bootstrap()ControlGroup()TextBoxFor(X => x.Name)。
        @ Html.Bootstrap()ControlGroup()TextBoxFor(X => x.Age)。
    < / DIV>
    < D​​IV CLASS =模式躯>
        <按钮类=BTN BTN-反类型=提交>保存< /按钮>
    < / DIV>
}
 

现在放在你的应用程序,说一个部分_peoplePartial.cshtml等:

 < D​​IV>
   @foreach(VAR人Model.People)
    {
        <按钮类=BTN BTN-主要编辑人数据ID =@ PERSON.PERSONID>编辑< /按钮>
    }
< / DIV>
//这是模态的定义
< D​​IV CLASS = ID =编辑人&GT模式隐藏在变脸;
    < D​​IV ID =编辑人集装箱>< / DIV>
< / DIV>

<脚本类型=文/ JavaScript的>
$(文件)。就绪(函数(){
    $('。编辑人)。点击(函数(){
        VAR URL =/人/ EditPerson; //的URL控制器
        VAR ID = $(本).attr(数据ID); //这给了每个按钮在列表中的id
        $获得(网址+/+ ID,功能(数据){
            $('#编辑人集装箱)HTML(数据)。
            $('#编辑人)模式('秀')。
        });
    });
 });
 

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 :

  • Should I use a simple or a partial view?
  • How can I perform the validation (actually it work but it redirects me to my original view so not in the modal form)

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');
        });
    });
 });

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆