简体   繁体   中英

Unobtrusive Client Validation in ASP.NET MVC 5 when calling web api in the back end

I have an index pagee with a button called "Add Owner". When this button is called, it displays a Bootstrap modal that has a form. When the form is posted (using jquery), all the fields are serialized and posted to the below action.

// POST: api/Owners
    [ResponseType(typeof(DisplayOwnerViewModel))]
    public IHttpActionResult PostOwner(DisplayOwnerViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        _unit.Owners.Add(model);
        _unit.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = model.Id }, model);
    }

And this is the page that is being posted to the this action.

@model xMDT.WebUI.Models.DisplayOwnerViewModel


@using (Html.BeginForm())
{
  @Html.AntiForgeryToken()

  <div class="form-horizontal">
  @Html.ValidationSummary(true, "", new { @class = "text-danger" })
  @Html.HiddenFor(model => model.Id)
  <div class="form-group">
      @Html.LabelFor(model => model.OwnerName, htmlAttributes: 
                              new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.OwnerName, 
                              new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.OwnerName, "", 
                              new { @class = "text-danger" })
        </div>
    </div>

    // many more ...

 }

When the post is successful, the bootstrap modal is hidden. However, when there's an error, such as the modelstate is invalid, how do I display errors on the page? As I see, when modelstate is not valid, the action return BadRequest(ModelState) .

And this is me javascript:

$('#btnSaveOwner').on('click', function () {
        var formData = $('#addEditModal .modal-body form').serialize();
        $.ajax({
            type: 'POST',
            url: '/api/owners',
            data: formData,
            success: function(result)
            {
                $('#addEditModal').modal('hide');
            },
            error: function()
            {
                alert('Some thing went wrong!')
            }
        });            
    });

Thanks for helping.

What I understand is, you want to display error message if the ModelState is not valid ie user has not given sufficient input. In that case, you can hold your action call (why even you need to call the action if there is insufficient input?). To check for validation, you can use kendoValidator.

Checkout this demo -

http://demos.telerik.com/kendo-ui/web/validator/index.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM