Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 具有服务器端验证的MVC引导PopOver_Asp.net Mvc_Twitter Bootstrap_Modal Dialog_Asp.net Mvc 5_Server Side Validation - Fatal编程技术网

Asp.net mvc 具有服务器端验证的MVC引导PopOver

Asp.net mvc 具有服务器端验证的MVC引导PopOver,asp.net-mvc,twitter-bootstrap,modal-dialog,asp.net-mvc-5,server-side-validation,Asp.net Mvc,Twitter Bootstrap,Modal Dialog,Asp.net Mvc 5,Server Side Validation,我有一个简单的MVC应用程序,它显示一个带有表单的引导PopOver模式。我想在提交数据时对表单运行一些服务器端验证。如果检测到错误,我希望应用程序在显示存储在ModelState中的任何错误的同时,保持现有表单打开,并保留用户的数据 当我在这个应用程序中直接调用“Create”视图时,表单会相应地显示错误。但是,当我使用Create视图作为模式时,它会显示错误消息,指出存在验证错误,但ValidationSummary不会显示错误详细信息 如何将数据从ModelState恢复到视图中 模型/M

我有一个简单的MVC应用程序,它显示一个带有表单的引导PopOver模式。我想在提交数据时对表单运行一些服务器端验证。如果检测到错误,我希望应用程序在显示存储在ModelState中的任何错误的同时,保持现有表单打开,并保留用户的数据

当我在这个应用程序中直接调用“Create”视图时,表单会相应地显示错误。但是,当我使用Create视图作为模式时,它会显示错误消息,指出存在验证错误,但ValidationSummary不会显示错误详细信息

如何将数据从ModelState恢复到视图中

模型/MyViewModel.cs

public class MyViewModel
{
    [Display(Name = "Field #1")]
    public string Field1 { get; set; }

    [Required(ErrorMessage = "Field2 is required.")]
    [StringLength(10)]
    [Display(Name = "Field #2")]
    public string Field2 { get; set; }
}
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Create()
    {
        var data = new MyViewModel {Field1 = "This is field 1!"};
        return PartialView("Create", data);
    }

    [HttpPost]
    public ActionResult Create(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {

            // There were validation errors. Don't lose the data the user entered on the page.
            // Do I need to return the modelstate here?
            return PartialView(model);
        }

        return Json(new { success = true });
    }
}
[HttpPost]
public ActionResult Create(MyViewModel model)
{
    if (!ModelState.IsValid)
    {
        var errors = new List<string>();

        foreach (var modelState in ViewData.ModelState.Values)
        {
            errors.AddRange(modelState.Errors.Select(error => error.ErrorMessage));
        }

        return Json(errors);
    }

    return Json(new { success = true });
}
  <div id="errorContainer" class="alert alert-danger" style="display: none">
    Validation issues:
    <div id="errors"></div>
  </div>
  function bindForm(dialog) {
    $('form', dialog).submit(function () {
      $.ajax({
        url: this.action,
        type: this.method,
        //traditional: true,
        data: $(this).serialize(),
        success: function (result) {
          if (result.success) {
            showValidationErrors(false);
            $('#simpleModal').modal('hide');
            alert('Validation was successful.');
          } else {
            fillErrorList(result);
            showValidationErrors(true);
          }
        }
      });
      return false;
    });

    function showValidationErrors(isShown) {
      if (isShown) {
        $("#errorContainer").show();
      } else {
        $("#errorContainer").hide();
      }
    }

    function fillErrorList(errors) {
      $("#errors").html("");

      var list = document.createElement('ul');

      for (var i = 0; i < errors.length; i++) {
        var item = document.createElement('li');
        item.appendChild(document.createTextNode(errors[i]));
        list.appendChild(item);
      }
      $("#errors").html(list);
    }
控制器/HomeController.cs

public class MyViewModel
{
    [Display(Name = "Field #1")]
    public string Field1 { get; set; }

    [Required(ErrorMessage = "Field2 is required.")]
    [StringLength(10)]
    [Display(Name = "Field #2")]
    public string Field2 { get; set; }
}
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Create()
    {
        var data = new MyViewModel {Field1 = "This is field 1!"};
        return PartialView("Create", data);
    }

    [HttpPost]
    public ActionResult Create(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {

            // There were validation errors. Don't lose the data the user entered on the page.
            // Do I need to return the modelstate here?
            return PartialView(model);
        }

        return Json(new { success = true });
    }
}
[HttpPost]
public ActionResult Create(MyViewModel model)
{
    if (!ModelState.IsValid)
    {
        var errors = new List<string>();

        foreach (var modelState in ViewData.ModelState.Values)
        {
            errors.AddRange(modelState.Errors.Select(error => error.ErrorMessage));
        }

        return Json(errors);
    }

    return Json(new { success = true });
}
  <div id="errorContainer" class="alert alert-danger" style="display: none">
    Validation issues:
    <div id="errors"></div>
  </div>
  function bindForm(dialog) {
    $('form', dialog).submit(function () {
      $.ajax({
        url: this.action,
        type: this.method,
        //traditional: true,
        data: $(this).serialize(),
        success: function (result) {
          if (result.success) {
            showValidationErrors(false);
            $('#simpleModal').modal('hide');
            alert('Validation was successful.');
          } else {
            fillErrorList(result);
            showValidationErrors(true);
          }
        }
      });
      return false;
    });

    function showValidationErrors(isShown) {
      if (isShown) {
        $("#errorContainer").show();
      } else {
        $("#errorContainer").hide();
      }
    }

    function fillErrorList(errors) {
      $("#errors").html("");

      var list = document.createElement('ul');

      for (var i = 0; i < errors.length; i++) {
        var item = document.createElement('li');
        item.appendChild(document.createTextNode(errors[i]));
        list.appendChild(item);
      }
      $("#errors").html(list);
    }
视图/Home/Index.chstml

@Html.ActionLink("Open the popover modal", "create", null, null, new { id = "modalLink" })
@Html.ActionLink("Navigate directly to the modal page", "Create", "Home")

    <script type="text/javascript">
      $(function () {
        $('#modalLink').click(function () {
          $('#dialog').load(this.href, function () {
            $('#simpleModal').modal('show');
            bindForm(this);
          });
          return false;
        });
      });

      function bindForm(dialog) {
        $('form', dialog).submit(function () {
          $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
              if (result.success) {
                alert('Validation was successful.');
                $('#simpleModal').modal('hide');
              } else {
                // Am I missing something here? 
                alert('Server validation failed!');
              }
            }
          });
          return false;
        });
      }
    </script>
@model MvcModalPopupWithValidation.Models.MyViewModel

@using (Html.BeginForm())
{
  <div class="modal fade" id="simpleModal" tabindex="-1" role="dialog" aria-labelledby="simpleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
          <h4 class="modal-title" id="simpleModalLabel">
            Modal Validation Test
          </h4>
        </div>
        <div class="modal-body">
          @Html.ValidationSummary(true)

          <div>
            @Html.LabelFor(x => x.Field1)
            @Html.EditorFor(x => x.Field1)
            @Html.ValidationMessageFor(x => x.Field1)
          </div>
          <div>
            @Html.LabelFor(x => x.Field2)
            @Html.EditorFor(x => x.Field2)
            @Html.ValidationMessageFor(x => x.Field2)
          </div>

        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary" id="btnDeclineModal">Save changes</button>
        </div>
      </div>
    </div>
  </div>
}
@Html.ActionLink(“打开popover模式”,“创建”,null,null,new{id=“modalLink”})
@ActionLink(“直接导航到模式页面”、“创建”、“主页”)
$(函数(){
$('#modalLink')。单击(函数(){
$('#dialog').load(this.href,函数(){
$('simpleModal').modal('show');
bindForm(本);
});
返回false;
});
});
函数绑定窗体(对话框){
$('form',dialog).submit(函数(){
$.ajax({
url:this.action,
类型:this.method,
数据:$(this).serialize(),
成功:功能(结果){
如果(结果、成功){
警报('验证成功');
$('simpleModal').modal('hide');
}否则{
//我是不是遗漏了什么?
警报('服务器验证失败!');
}
}
});
返回false;
});
}
查看/Home/Create.cshtml

@Html.ActionLink("Open the popover modal", "create", null, null, new { id = "modalLink" })
@Html.ActionLink("Navigate directly to the modal page", "Create", "Home")

    <script type="text/javascript">
      $(function () {
        $('#modalLink').click(function () {
          $('#dialog').load(this.href, function () {
            $('#simpleModal').modal('show');
            bindForm(this);
          });
          return false;
        });
      });

      function bindForm(dialog) {
        $('form', dialog).submit(function () {
          $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
              if (result.success) {
                alert('Validation was successful.');
                $('#simpleModal').modal('hide');
              } else {
                // Am I missing something here? 
                alert('Server validation failed!');
              }
            }
          });
          return false;
        });
      }
    </script>
@model MvcModalPopupWithValidation.Models.MyViewModel

@using (Html.BeginForm())
{
  <div class="modal fade" id="simpleModal" tabindex="-1" role="dialog" aria-labelledby="simpleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
          <h4 class="modal-title" id="simpleModalLabel">
            Modal Validation Test
          </h4>
        </div>
        <div class="modal-body">
          @Html.ValidationSummary(true)

          <div>
            @Html.LabelFor(x => x.Field1)
            @Html.EditorFor(x => x.Field1)
            @Html.ValidationMessageFor(x => x.Field1)
          </div>
          <div>
            @Html.LabelFor(x => x.Field2)
            @Html.EditorFor(x => x.Field2)
            @Html.ValidationMessageFor(x => x.Field2)
          </div>

        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary" id="btnDeclineModal">Save changes</button>
        </div>
      </div>
    </div>
  </div>
}
@model MvcModalPopupWithValidation.Models.MyViewModel
@使用(Html.BeginForm())
{
&时代;
模态验证试验
@Html.ValidationSummary(true)
@LabelFor(x=>x.Field1)
@EditorFor(x=>x.Field1)
@Html.ValidationMessageFor(x=>x.Field1)
@LabelFor(x=>x.Field2)
@EditorFor(x=>x.Field2)
@Html.ValidationMessageFor(x=>x.Field2)
接近
保存更改
}

我确实设法让服务器端验证正常工作。我仍然希望有人能拿出正确的、更好的或自动神奇的方法来实现这一点

如果有人遇到与我相同的困难,下面是我必须进行的代码更改,以使其正常工作

控制器更改

public class MyViewModel
{
    [Display(Name = "Field #1")]
    public string Field1 { get; set; }

    [Required(ErrorMessage = "Field2 is required.")]
    [StringLength(10)]
    [Display(Name = "Field #2")]
    public string Field2 { get; set; }
}
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Create()
    {
        var data = new MyViewModel {Field1 = "This is field 1!"};
        return PartialView("Create", data);
    }

    [HttpPost]
    public ActionResult Create(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {

            // There were validation errors. Don't lose the data the user entered on the page.
            // Do I need to return the modelstate here?
            return PartialView(model);
        }

        return Json(new { success = true });
    }
}
[HttpPost]
public ActionResult Create(MyViewModel model)
{
    if (!ModelState.IsValid)
    {
        var errors = new List<string>();

        foreach (var modelState in ViewData.ModelState.Values)
        {
            errors.AddRange(modelState.Errors.Select(error => error.ErrorMessage));
        }

        return Json(errors);
    }

    return Json(new { success = true });
}
  <div id="errorContainer" class="alert alert-danger" style="display: none">
    Validation issues:
    <div id="errors"></div>
  </div>
  function bindForm(dialog) {
    $('form', dialog).submit(function () {
      $.ajax({
        url: this.action,
        type: this.method,
        //traditional: true,
        data: $(this).serialize(),
        success: function (result) {
          if (result.success) {
            showValidationErrors(false);
            $('#simpleModal').modal('hide');
            alert('Validation was successful.');
          } else {
            fillErrorList(result);
            showValidationErrors(true);
          }
        }
      });
      return false;
    });

    function showValidationErrors(isShown) {
      if (isShown) {
        $("#errorContainer").show();
      } else {
        $("#errorContainer").hide();
      }
    }

    function fillErrorList(errors) {
      $("#errors").html("");

      var list = document.createElement('ul');

      for (var i = 0; i < errors.length; i++) {
        var item = document.createElement('li');
        item.appendChild(document.createTextNode(errors[i]));
        list.appendChild(item);
      }
      $("#errors").html(list);
    }
[HttpPost]
公共操作结果创建(MyViewModel模型)
{
如果(!ModelState.IsValid)
{
var errors=新列表();
foreach(ViewData.modelState.Values中的var modelState)
{
errors.AddRange(modelState.errors.Select(error=>error.ErrorMessage));
}
返回Json(错误);
}
返回Json(新的{success=true});
}
Create.cshtml更改

public class MyViewModel
{
    [Display(Name = "Field #1")]
    public string Field1 { get; set; }

    [Required(ErrorMessage = "Field2 is required.")]
    [StringLength(10)]
    [Display(Name = "Field #2")]
    public string Field2 { get; set; }
}
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Create()
    {
        var data = new MyViewModel {Field1 = "This is field 1!"};
        return PartialView("Create", data);
    }

    [HttpPost]
    public ActionResult Create(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {

            // There were validation errors. Don't lose the data the user entered on the page.
            // Do I need to return the modelstate here?
            return PartialView(model);
        }

        return Json(new { success = true });
    }
}
[HttpPost]
public ActionResult Create(MyViewModel model)
{
    if (!ModelState.IsValid)
    {
        var errors = new List<string>();

        foreach (var modelState in ViewData.ModelState.Values)
        {
            errors.AddRange(modelState.Errors.Select(error => error.ErrorMessage));
        }

        return Json(errors);
    }

    return Json(new { success = true });
}
  <div id="errorContainer" class="alert alert-danger" style="display: none">
    Validation issues:
    <div id="errors"></div>
  </div>
  function bindForm(dialog) {
    $('form', dialog).submit(function () {
      $.ajax({
        url: this.action,
        type: this.method,
        //traditional: true,
        data: $(this).serialize(),
        success: function (result) {
          if (result.success) {
            showValidationErrors(false);
            $('#simpleModal').modal('hide');
            alert('Validation was successful.');
          } else {
            fillErrorList(result);
            showValidationErrors(true);
          }
        }
      });
      return false;
    });

    function showValidationErrors(isShown) {
      if (isShown) {
        $("#errorContainer").show();
      } else {
        $("#errorContainer").hide();
      }
    }

    function fillErrorList(errors) {
      $("#errors").html("");

      var list = document.createElement('ul');

      for (var i = 0; i < errors.length; i++) {
        var item = document.createElement('li');
        item.appendChild(document.createTextNode(errors[i]));
        list.appendChild(item);
      }
      $("#errors").html(list);
    }

验证问题:
Index.cshtml更改

public class MyViewModel
{
    [Display(Name = "Field #1")]
    public string Field1 { get; set; }

    [Required(ErrorMessage = "Field2 is required.")]
    [StringLength(10)]
    [Display(Name = "Field #2")]
    public string Field2 { get; set; }
}
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Create()
    {
        var data = new MyViewModel {Field1 = "This is field 1!"};
        return PartialView("Create", data);
    }

    [HttpPost]
    public ActionResult Create(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {

            // There were validation errors. Don't lose the data the user entered on the page.
            // Do I need to return the modelstate here?
            return PartialView(model);
        }

        return Json(new { success = true });
    }
}
[HttpPost]
public ActionResult Create(MyViewModel model)
{
    if (!ModelState.IsValid)
    {
        var errors = new List<string>();

        foreach (var modelState in ViewData.ModelState.Values)
        {
            errors.AddRange(modelState.Errors.Select(error => error.ErrorMessage));
        }

        return Json(errors);
    }

    return Json(new { success = true });
}
  <div id="errorContainer" class="alert alert-danger" style="display: none">
    Validation issues:
    <div id="errors"></div>
  </div>
  function bindForm(dialog) {
    $('form', dialog).submit(function () {
      $.ajax({
        url: this.action,
        type: this.method,
        //traditional: true,
        data: $(this).serialize(),
        success: function (result) {
          if (result.success) {
            showValidationErrors(false);
            $('#simpleModal').modal('hide');
            alert('Validation was successful.');
          } else {
            fillErrorList(result);
            showValidationErrors(true);
          }
        }
      });
      return false;
    });

    function showValidationErrors(isShown) {
      if (isShown) {
        $("#errorContainer").show();
      } else {
        $("#errorContainer").hide();
      }
    }

    function fillErrorList(errors) {
      $("#errors").html("");

      var list = document.createElement('ul');

      for (var i = 0; i < errors.length; i++) {
        var item = document.createElement('li');
        item.appendChild(document.createTextNode(errors[i]));
        list.appendChild(item);
      }
      $("#errors").html(list);
    }
函数绑定表单(对话框){
$('form',dialog).submit(函数(){
$.ajax({
url:this.action,
类型:this.method,
//传统的:是的,
数据:$(this).serialize(),
成功:功能(结果){
如果(结果、成功){
showValidationErrors(假);
$('simpleModal').modal('hide');
警报('验证成功');
}否则{
填写错误列表(结果);
showValidationErrors(true);
}
}
});
返回false;
});
函数showValidationErrors(isShown){
如果(isShown){
$(“#errorContainer”).show();
}否则{
$(“#errorContainer”).hide();
}
}
函数fillErrorList(错误){
$(“#错误”).html(“”);
var list=document.createElement('ul');
对于(变量i=0;i