When model is not valid, return to partial view in

2019-07-19 11:40发布

问题:

I´ve got a modal boostrap. I want to show the error of validation on boostrap modal. But when I leave the model empty and click on submit button Its just viewed as a standalone page.

Partial view:

  @model WebApplication1.Models.Book

<form asp-controller="Home" asp-action="AddBook"
  data-ajax="true" data-ajax-method="POST" data-ajax-mode="replace" data-ajax-update="#frmaddbook">

<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="myModalLabel">Header of Modal</h4>
</div>

<div class="modal-body form-horizontal" id="frmaddbook  ">

    <span class="alert-danger">
        @Html.ValidationSummary()
    </span>

    <div class="row">
        <div class="form-group">
            <label asp-for="BookName" class="col-lg-3 col-sm-3 control-label"></label>
            <div class="col-lg-6">
                <input asp-for="BookName" class="form-control" />
                <span asp-validation-for="BookName" class="text-danger"></span>
            </div>
        </div>

        <div class="form-group">
            <label asp-for="BookDescription" class="col-lg-3 col-sm-3 control-label"></label>
            <div class="col-lg-6">
                <input asp-for="BookDescription" class="form-control" />
                <span asp-validation-for="BookDescription" class="text-danger"></span>
            </div>
        </div>
    </div>
</div>


<div class="modal-footer">
    <input type="submit" class="btn btn-primary" value="Submit" />
</div>

Index View :

<div class="panel panel-primary">
<div class="panel-body">
    <div class="btn-group">
        <a class="btn btn-primary marginbutoon" id="showBookgroup" data-toggle="modal" asp-action="AddBook"
           data-target="#modal-book">
            <i class="glyphicon glyphicon-plus"></i>
            Add Book
        </a>
    </div>
</div>

i use this libraries at top of index view:

  1. jquery.unobtrusive-ajax.min.js
  2. jquery.validate.unobtrusive.min.js

and use at the bottom of index view:

  <script src="~/js/book-index.js"></script>

book-index.js:

(function ($) {
function Home() {
    var $this = this;

    function initilizeModel() {
        $("#modal-book").on('loaded.bs.modal', function (e) {

        }).on('hidden.bs.modal', function (e) {
            $(this).removeData('bs.modal');
        });
    }
    $this.init = function () {
        initilizeModel();
    }
}
$(function () {
    var self = new Home();
    self.init();
})

}(jQuery))

Controller:

     [HttpGet]
    public IActionResult AddBook()
    {
        var b = new Book();

        return PartialView("_AddBook", b);
    }



    [HttpPost]
    [ValidateAntiForgeryToken]
    //[HandleError]//not in core
    public IActionResult AddBook(Book model)
    {
        if (ModelState.IsValid)
        {
            return RedirectToAction("Index");
        }

        return PartialView("_AddBook", model);
    }

Model :

public class Book
{

    [Key]
    public int BookId { get; set; }

    [Display(Name = "Book Name :")]
    [Required(ErrorMessage = "Enter Book Name Please ")]
    public string BookName { get; set; }


    [Display(Name = "Book Description")]
    [Required(ErrorMessage = "Enter Book Description Please ")]

    public string BookDescription { get; set; }
}

My code is shown above. How can i show validation error in modal partial view ?

回答1:

You can set the Id of form as the data-ajax-update property value of the form , which is ajaxified. This value will be used as the jQuery selector when the result is received from the ajax call.

@model Book
<form asp-controller="Home" asp-action="AddBook" id="myform"
      data-ajax="true" data-ajax-method="POST"
                                 data-ajax-mode="replace" data-ajax-update="#myform">

    <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="myModalLabel">Add Book</h4>
    </div>

    <div class="modal-body form-horizontal" id="frmaddbook  ">

        <span class="alert-danger">
            @Html.ValidationSummary()
        </span>

        <div class="row">
            <div class="form-group">
                <label asp-for="BookName" class="col-sm-3 control-label"></label>
                <div class="col-lg-6">
                    <input asp-for="BookName" class="form-control" />
                    <span asp-validation-for="BookName" class="text-danger"></span>
                </div>
            </div>
        </div>
    </div>
    <div class="modal-footer">
        <input type="submit" class="btn btn-primary" value="Submit" />
    </div>
</form>

Now when you submit the form and model state validation fails, the action method code will return the partial view result with the validation error messages (generated by the validation helpers) and the jquery.unobtrusive-ajax.js library code will replace (because we specified that with data-ajax-mode="replace") the content of the result of the jquery selector #data-ajax-update (the form tag and it's inner contents) with the response coming back from the server.