MVC 4使用Bootstrap编辑模态表单

时间:2013-04-15 08:51:40

标签: c# jquery ajax asp.net-mvc twitter-bootstrap

我正在使用MVC 4和Entity Framework来开发Intranet Web应用程序。我有一个可以通过编辑操作修改的人员列表。我想通过使用模态表单使我的应用程序更具动态性。所以我试着把我的编辑视图放到我的Bootstrap模态中,我有两个问题:

  • 我应该使用简单或部分视图吗?
  • 我如何执行验证(实际上它可以工作,但它会将我重定向到原始视图,因此不会以模态形式重定向)

我想我必须使用AJAX和/或jQuery,但我是这些技术的新手。任何帮助将不胜感激。

编辑:我的索引视图:

@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>
}

我的部分观点:

@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>
}

4 个答案:

答案 0 :(得分:52)

您应该使用部分视图。我使用以下方法:

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

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

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

接下来创建一个名为_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">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>
}

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

<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>

答案 1 :(得分:20)

我更喜欢避免使用Ajax.BeginForm帮助程序并使用JQuery进行Ajax调用。根据我的经验,维护这样编写的代码更容易。以下是详细信息:

<强>模型

public class ManagePeopleModel
{
    public List<PersonModel> People { get; set; }
    ... any other properties
}

public class PersonModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    ... any other properties
}

家长视图

此视图包含以下内容:

  • 迭代的人员记录
  • 当需要编辑人员时,将使用模态填充的空div
  • 处理所有ajax调用的一些JavaScript
@model ManagePeopleModel

<h1>Manage People</h1>

@using(var table = Html.Bootstrap().Begin(new Table()))
{
    foreach(var person in Model.People)
    {
        <tr>
            <td>@person.Id</td>
            <td>@Person.Name</td>
            <td>@person.Age</td>
            <td>@html.Bootstrap().Button().Text("Edit Person").Data(new { @id = person.Id }).Class("btn-trigger-modal")</td>
        </tr>
    }
}

@using (var m = Html.Bootstrap().Begin(new Modal().Id("modal-person")))
{

}

@section Scripts
{
    <script type="text/javascript">
        // Handle "Edit Person" button click.
        // This will make an ajax call, get information for person,
        // put it all in the modal and display it
        $(document).on('click', '.btn-trigger-modal', function(){
            var personId = $(this).data('id');
            $.ajax({
                url: '/[WhateverControllerName]/GetPersonInfo',
                type: 'GET',
                data: { id: personId },
                success: function(data){
                    var m = $('#modal-person');
                    m.find('.modal-content').html(data);
                    m.modal('show');
                }
            });
        });

        // Handle submitting of new information for Person.
        // This will attempt to save new info
        // If save was successful, it will close the Modal and reload page to see updated info
        // Otherwise it will only reload contents of the Modal
        $(document).on('click', '#btn-person-submit', function() {
            var self = $(this);
            $.ajax({
                url: '/[WhateverControllerName]/UpdatePersonInfo',
                type: 'POST',
                data: self.closest('form').serialize(),
                success: function(data) {
                    if(data.success == true) {
                        $('#modal-person').modal('hide');
                        location.reload(false)
                    } else {
                        $('#modal-person').html(data);
                    }
                }
            });
        });
    </script>
}

部分视图

此视图包含一个将填充有关人员信息的模式。

@model PersonModel
@{
    // get modal helper
    var modal = Html.Bootstrap().Misc().GetBuilderFor(new Modal());
}

@modal.Header("Edit Person")
@using (var f = Html.Bootstrap.Begin(new Form()))
{
    using (modal.BeginBody())
    {
        @Html.HiddenFor(x => x.Id)
        @f.ControlGroup().TextBoxFor(x => x.Name)
        @f.ControlGroup().TextBoxFor(x => x.Age)
    }
    using (modal.BeginFooter())
    {
        // if needed, add here @Html.Bootstrap().ValidationSummary()
        @:@Html.Bootstrap().Button().Text("Save").Id("btn-person-submit")
        @Html.Bootstrap().Button().Text("Close").Data(new { dismiss = "modal" })
    }
}

控制器操作

public ActionResult GetPersonInfo(int id)
{
    var model = db.GetPerson(id); // get your person however you need
    return PartialView("[Partial View Name]", model)
}

public ActionResult UpdatePersonInfo(PersonModel model)
{
    if(ModelState.IsValid)
    {
        db.UpdatePerson(model); // update person however you need
        return Json(new { success = true });
    }
    // else
    return PartialView("[Partial View Name]", model);
}

答案 2 :(得分:3)

回复Dimitrys答案,但使用Ajax.BeginForm以下作品至少使用MVC&gt; 5(4未经测试)。

  1. 写一个模型,如其他答案所示,

  2. 在“父视图”中,您可能会使用表格来显示数据。 模型应该是一个不可数的。我假设,该模型具有id - 属性。但是在模板下面,是模态的占位符和相应的javascript

    <table>
    @foreach (var item in Model)
    {
        <tr> <td id="editor-success-@item.Id"> 
            @Html.Partial("dataRowView", item)
        </td> </tr>
    }
    </table>
    
    <div class="modal fade" id="editor-container" tabindex="-1" 
         role="dialog" aria-labelledby="editor-title">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content" id="editor-content-container"></div>
        </div>
    </div> 
    
    <script type="text/javascript">
        $(function () {
            $('.editor-container').click(function () {
                var url = "/area/controller/MyEditAction";  
                var id = $(this).attr('data-id');  
                $.get(url + '/' + id, function (data) {
                    $('#editor-content-container').html(data);
                    $('#editor-container').modal('show');
                });
            });
        });
    
        function success(data,status,xhr) {
            $('#editor-container').modal('hide');
            $('#editor-content-container').html("");
        }
    
        function failure(xhr,status,error) {
            $('#editor-content-container').html(xhr.responseText);
            $('#editor-container').modal('show');
        }
    </script>
    
  3. 请注意数据表行中的“editor-success-id”。

    1. dataRowView是部分包含模型项目的表示。

      @model ModelView
      @{
          var item = Model;
      }
      <div class="row">
              // some data 
              <button type="button" class="btn btn-danger editor-container" data-id="@item.Id">Edit</button>
      </div>
      
    2. 通过单击行的按钮(通过JS $('.editor-container').click(function () ...)编写调用的局部视图。

      @model Model
      <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
          </button>
          <h4 class="modal-title" id="editor-title">Title</h4>
      </div>
      @using (Ajax.BeginForm("MyEditAction", "Controller", FormMethod.Post,
                          new AjaxOptions
                          {
                              InsertionMode = InsertionMode.Replace,
                              HttpMethod = "POST",
                              UpdateTargetId = "editor-success-" + @Model.Id,
                              OnSuccess = "success",
                              OnFailure = "failure",
                          }))
      {
          @Html.ValidationSummary()
          @Html.AntiForgeryToken()
          @Html.HiddenFor(model => model.Id)
          <div class="modal-body">
              <div class="form-horizontal">
                  // Models input fields
              </div>
          </div>
          <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
              <button type="submit" class="btn btn-primary">Save</button>
          </div>
      }
      
    3. 这就是魔术发生的地方:在AjaxOptions中,UpdateTargetId将在编辑后替换数据行,onfailure和onsuccess将控制模态。

      这就是,模态只会在编辑成功并且没有错误时关闭,否则在ajax-posting之后将显示模态以显示错误消息,例如验证摘要。

      但是如何让ajaxform知道是否有错误?这是控制器部分,只需在步骤5中更改response.statuscode,如下所示:

      1. 部分编辑模式的相应控制器操作方法

        [HttpGet]
        public async Task<ActionResult> EditPartData(Guid? id)
        {
            // Find the data row and return the edit form
            Model input = await db.Models.FindAsync(id);
            return PartialView("EditModel", input);
        }
        
        [HttpPost, ValidateAntiForgeryToken]
        public async Task<ActionResult> MyEditAction([Bind(Include =
           "Id,Fields,...")] ModelView input)
        {
            if (TryValidateModel(input))
            {  
                // save changes, return new data row  
                // status code is something in 200-range
                db.Entry(input).State = EntityState.Modified;
                await db.SaveChangesAsync();
                return PartialView("dataRowView", (ModelView)input);
            }
        
            // set the "error status code" that will redisplay the modal
            Response.StatusCode = 400;
            // and return the edit form, that will be displayed as a 
            // modal again - including the modelstate errors!
            return PartialView("EditModel", (Model)input);
        }
        
      2. 这样,如果在模态窗口中编辑模型数据时发生错误,则错误将显示在带有MVC验证方法的模态中;但如果成功提交了更改,则会显示修改后的数据表,并且模态窗口将消失。

        注意:你得到ajaxoptions工作,你需要告诉你的bundle配置绑定jquery.unobtrusive-ajax.js(可能由NuGet安装):

                bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
                            "~/Scripts/jquery.unobtrusive-ajax.js"));
        

答案 3 :(得分:0)

$('.editor-container').click(function (){})中,var url = "/area/controller/MyEditAction";不应该是var url = "/area/controller/EditPartData";吗?