1

Hi I am trying to validate one dropdown if was selected this way:

$('#dialog').dialog({
            autoOpen: false,
            width: 400,
            resizable: false,
            title: 'Add building',
            modal: true,
            open: function(event, ui) {

                $(this).load("@Url.Action("AddView",new {@ViewBag.from})");
            },
            buttons: {
                "Add": function () {
                    $("#LogOnForm").submit();
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            }
        });

view

@model View.ViewModel.AddBuildingViewModel


@{Html.EnableClientValidation();}

@using (Html.BeginForm("AddBuilding", "HolidaysEvents", FormMethod.Post, new { id = "LogOnForm" }))
{
    @Html.HiddenFor(x => x.ReqestFrom, new { @Value = @ViewBag.from })
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Building</legend>

        <table>
            <tr>
                <td>
                    <div class="editor-label">
                        @Html.LabelFor(model => model.Building.Name)
                    </div>

                </td>
                <td>
                    <div class="editor-field">
                        @Html.TextBoxFor(model => model.Building.Name)
                        @Html.ValidationMessageFor(model => model.Building.Name)
                    </div>
                </td>
            </tr>
            <tr>
                <td>
                    Country
                </td>

                <td>
                    <div class="editor-label">
                        @Html.DropDownListFor(model => model.Building.CountryId, new SelectList(Model.Countries, "Id", "Name"), "Choose Country... ", new { style = "height:35px"})
                        @Html.ValidationMessageFor(model => model.Building.CountryId)
                    </div>
                </td>

            </tr>

        </table>

        <p>
            <input type="submit" value="Log On" style="display:none;" />
        </p>
    </fieldset>
}

model

public class BuildingViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }

        [Required(ErrorMessage = "Required.")]
        public int CountryId { get; set; }
    }

code

[HttpPost]
        public ActionResult AddBuilding(AddBuildingViewModel buildingModel)
        {
            if (!ModelState.IsValid)
            {
                var modelError = new AddBuildingViewModel();
                modelError.Countries = countryRepository.GetCountries().Select(x => new CountryViewModel { Id = x.Id, Name = x.Name }).ToList();
                return PartialView("AddView", modelError);
            }


            var model = new HolidaysEventsViewModel();
            buildingRepository.AddBuilding(buildingModel.Building.Name, buildingModel.Building.CountryId, WebSecurity.CurrentUserId);


            model.Buildings = buildingRepository.GetBuildings(WebSecurity.CurrentUserId).Select(x => new BuildingViewModel { Id = x.Id, Name = x.Name }).ToList();
            model.Countries = countryRepository.GetCountries().Select(x => new CountryViewModel {Id = x.Id, Name = x.Name}).ToList();
            ViewBag.from = buildingModel.ReqestFrom;
            return View("Index", model);
        }

and the problem is that when user didn't select anything and validation works then dialog dissapears and instaed of it is just pure html page with validation message, how can I prevnt it and keep popup ?

1 Answer 1

2

If you want to keep the modal dialog open you'll need to use AJAX. Instead of $("#LogOnForm").submit() you'll need to convert this to an AJAX POST submission and use its callback to replace the dialog's form with your partial view result.

Here's an outline of what to do:

First, you'll need to modify your dialog to accept the partial.

<div id="dialog">
    <div id="content">
       <!-- partial view inserted here -->
    </div>
</div>

Now insert the partial view form into the dialog.

open: function(event, ui) {
    $("#content").load("@Url.Action("AddView",new {@ViewBag.from})");
}

AJAX post so you don't navigate away from this page.

"Add": function() {
    $.ajax({
        url: "/HolidayEvents/AddBuilding",
        type: "POST",
        data: $("#LogOnForm").serialize()
    })
    .done(function(partialResult) {
        // validation error OR success
        $("#content").html(partialResult);
    });
}

You may also need to prevent the default behavior on form submission because you handle the submission via AJAX.

$("#LogOnForm").on("submit", function(e) {
    e.preventDefault();
});

Your action returns a partial view to the partialResult in the callback.

[HttpPost]
public ActionResult AddBuilding(AddBuildingViewModel buildingModel)
{
    if (!ModelState.IsValid)
    {
        ...
        return PartialView("AddView", modelError);
    }

    ...
    return PartialView("SuccessView", model);
}

Since we used AJAX, the browser navigation to "Index" won't happen, so replace the dialog content with a success view. The success view will need a verify button so the user can close the dialog or navigate away to a new page..

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.