2

I'm currently working on a ASP.NET MVC 4 project as a trainee and I'm trying to implement an admin panel. The goal is to show all the users on a grid (MVC.GRID) and edit them on the same page. I've managed to show all the users on the grid and once a user is selected it shows the info below the grid and puts it in a form (via ajax/jquery).

The problem is: the form validation is being displayed on a new page and not on the page where the grid is at. And I've no idea why..

Below is my code.

This is where the form is placed:

<div id="order-content">
  <p class="muted">
    Select a user to see his or her information
  </p>
</div>

The form itself (partial view "_UserInfo):

@using (Ajax.BeginForm("EditUser", "Admin", FormMethod.Post, 
  new AjaxOptions
  {
    InsertionMode = InsertionMode.Replace,
    HttpMethod = "POST",
    UpdateTargetId = "order-content"
  }))
{
  @Html.Bootstrap().ValidationSummary()
  @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Id)
  @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Name)
  @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Password)
  @Html.Bootstrap().SubmitButton().Text("Opslaan").Style(ButtonStyle.Primary)
}

JQuery to show the user info once a row is selected:

$(function () {
pageGrids.usersGrid.onRowSelect(function (e) {
  $.post("/Admin/GetUser?id=" + e.row.Id, function (data) {
    if (data.Status <= 0) {
      alert(data.Message);
      return;
    }
    $("#order-content").html(data.Content);
  });
});
});

My AdminController:

[HttpPost]
public JsonResult GetUser(int id)
{
  var user = _UserService.Get(id);
  var input = _EditInputMapper.MapToInput(user);
  if (user == null)
    return Json(new { Status = 0, Message = "Not found" });

  return Json(new { Content = RenderPartialViewToString("_UserInfo", input) });
}

[HttpPost]
public ActionResult EditUser(AdminUserEditInput input)
{
  if (ModelState.IsValid)
  {
    // todo: update the user
    return View();
  }
  // This is where it probably goes wrong..
  return PartialView("_UserInfo",input);
}

Can anyone see what is wrong with my code?

Thank you.

4

2 回答 2

0

我现在可以工作了。使用 jsonvalidator。我不知道这是否是一个好的解决方案,但它现在可以完成工作..

这就是我在AdminController中所做的更改

[HttpPost]
public ActionResult EditUser(AdminUserEditInput input)
{
  int id = (int)TempData["UserID"];

  if (ModelState.IsValid)
  {
    _UserService.ChangeMail(id, input.Mail);
    _UserService.ChangeName(id, input.Firstname, input.Name);

    return new RedirectResult(Url.Action("Users", "Admin") + "#id=" + id);
  }
  else
  {

    return new JsonResult { Data = new { Valid = false, Errors = Validator.CheckModelErrors(ModelState) } };
  }
}

添加了一个JsonValidator类:

  public static class Validator // todo: doesn't belong in the controllers directory ?
  {
    public static List<JsonError> CheckModelErrors(System.Web.Mvc.ModelStateDictionary modelstate)
    {
      List<JsonError> errorlist = new List<JsonError>();
      if (modelstate != null && modelstate.Values != null)
      {
        foreach (var m in modelstate.Values)
        {
          if (m.Errors != null)
          {
            foreach (var e in m.Errors)
            {
              errorlist.Add(new JsonError() { ErrorMessage = e.ErrorMessage ?? "" });
            }
          }
        }
      }
      return errorlist;
    }
  }

还有一个JsonError类..

  public class JsonError // todo: doesn't belong in the controllers directory ?
  {
    public string ErrorMessage { get; set; }
    public bool HasError { get; set; }
    public bool CanPerform { get; set; }
  }

最后但同样重要的是,js:

$(document).on('submit', '#UserForm', function (e) {
    e.defaultPrevented();
    $('#UserForm').validate();
    $.post($(this).attr("action"), $(this).serialize(), function (json) {
      if (json.Valid) {
        $("#order-content").html('<p class="muted"> Select a user.</p>');
      }
      else {
        $("#ShowValidation").empty();
        var list = $("#ShowValidation").append('<ul></ul>').find('ul');
        $.each(json.Errors, function (index, optionData) {
          list.append('<li>' + optionData.ErrorMessage + '</li>');
        })
      }
    }, "json");
  });

我正在考虑另一种管理方法,因为这只是暂时的。将输入与验证消息一起存储在会话中并让 js 将其放入 _UserInfo 视图中是否是个好主意?

于 2013-10-16T14:46:39.957 回答
0

当 ModelState 有效并且您返回 View() 时,此完整视图是否嵌入到订单内容中?我怀疑不是,如果是这样,那是因为没有发送 ajax 请求。您可能没有包含 jquery.unobtrusive-ajax js 文件

于 2013-10-01T12:20:56.240 回答