Friday 19 July 2013

Using Partial View and AJAX for Validation - with jQuery Ajax

In the previous post I wrote about using partial view for validation with Ajax.BeginForm. If we want to do the form submission manually with jQuery Ajax method we could do that as well. We only need to do minor changes on the partial view and add the jQuery script. Below is the updated partial view:
@model DTO.ItemSellingDto

<div id="result">
@using (Html.BeginForm("CreateEditPartial", "ItemSellings", FormMethod.Post, new {id="ItemSellingForm"})) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>ItemSelling</legend>
        <span style="color: red">@ViewBag.ErrorMessage</span>
        
        <div class="editor-label">
            @Html.LabelFor(model => model.Quantity)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Quantity)
            @Html.ValidationMessageFor(model => model.Quantity)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Price)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Price)
            @Html.ValidationMessageFor(model => model.Price)
        </div>

        . . .

        <div>
            <input id="btnCreateItemSelling" type="submit" value="Create" />
        </div>
    </fieldset>
}
</div>

<script type="text/javascript">
    $(function () {
        $('#ItemSellingForm').submit(function () {   // the form id is specified in Html.BeginForm method parameter
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (typeof result == 'object') {
                        $('#result').html('');  // this is to clear the update pane
                        addRow(result);
                    } else {
                        $('#result').html(result);  // display partial view again if input is not valid
                    }
                }
            });
            return false;  // don't forget this, otherwise the page will redirect
        });
    });
</script>
The other codes are still the same as shown here.

No comments: