ASP.NET MVC使用部分视图作为对话

时间:2016-04-01 13:20:28

标签: c# asp.net-mvc

我有一个ASP.NET MVC应用程序。此应用程序有一个显示记录列表的视图。我想让我的用户在此列表中添加记录。为此,我创建了一个用户可以输入信息的对话框。这时,这个对话框是局部的。我愿意改变实施方式。我只需要一个添加对话框。目前,我的观点如下:

Index.cshtml

<table class="table">
  <thead>
    <tr>
      <th></th>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Email address</th>
    </tr>
  </thead>

  <tbody>
    @foreach (var user in Model.Users)
    {
      <tr>
        <td></td>
        <td>@user.FirstName</td>
        <td>@user.LastName</td>
        <td>@user.Email</td>
      </tr>
    }
  </tbody>
</table>
<br />
<button type="button" class="btn btn-default" onclick="addPerson()">Add Person</button>

@* Add Person dialog *@
<div id="addPersonModal" class="modal">
  <div class="modal-dialog">
    @{Html.RenderAction("Add", "Person");}
  </div>
</div>

<script type="text/javascript">
  function addPerson() {
    $('#addPersonModal').modal('show');
  }
</script>

Add.cshtml

@model MyApp.Models.AddPersonModel
@{ Layout = null; }

<div class="modal-content">
@using(Html.BeginForm("Add", "Person", FormMethod.Post))
{
  <div class="modal-header">
    <h4 class="modal-title">Add New Person</h4>
  </div>

  <div class="modal-body">
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    <div class="row">
      <div class="col-md-6">
        @Html.TextBoxFor(m => m.FirstName)
      </div>

      <div class="col-md-6">
        @Html.TextBoxFor(m => m.LastName)
      </div>
    </div>

    <div class="row">
      <div class="col-md-12">
        @Html.TextBoxFor(m => m.Email)
      </div>
    </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">Create</button>
  </div>
  @Html.AntiForgeryToken()
}
</div>

PersonController.cs

namespace MyApp.Controllers
{
  public class PersonController : Controller
  {
    public ActionResult Index()
    {
      var model = new IndexModel();
      return View(model);
    }

    public ActionResult Add()
    {
      var model = new AddPersonModel();
      return View(model);
    }

    [HttpPost]
    public ActionResult Add(AddPersonModel model)
    {
      if (ModelState.IsValid)
      {
        model.Save();    
      }
      else 
      {
        // I'm stuck here.
      }    

      var listModel = new IndexModel();
      return View("~/Views/Person/Index.cshtml", listModel );
    }
  }
}

除验证外,一切正常。如果用户输入了一些无效数据,视图将重新加载整个屏幕并丢失数据。该对话框也已关闭。如果数据无效,我需要能够在对话框窗口中显示用户输入的值和验证摘要。但是,我不知道该怎么做。

0 个答案:

没有答案