简体   繁体   中英

MVC3 using Ajax.BeginForm not sending ViewModel to controller

I don't quite understand how to work the Ajax.BeginForm and the interactions with my controller. Here's my situation. I have a page with a list of items. When I click edit next to the item, a jquery dialog box opens with a strongly typed partial view containing fields to edit. When I click Update, I want to save my changes if the viewmodel is valid, or display the errors if necessary. My problem is when I click Update. I can't get to the point where I can send my serialized data to the controller as a viewmodel.

Edit: Ok, I found 1 problem. My form tag wasn't properly formed, so the form fields were outside of the form. Now I have a problem with the serializing of the form. I get this message: Invalid JSON primitive: section_id.

Here is my serialized string:

section_id=74&section_name_en=The+CF+Mission&section_name_fr=La+mission+des+FC&norm_tab_name_en=Introduction&norm_tab_name_fr=Introduction&section_tab_id=2&active=true&active=false&display_order=100&banner=banner.jpg&tab_title_en=Introduction&tab_title_fr=Introduction&content_id=17&content_text_en=%3Cdiv%3E%26nbsp%3B%3C%2Fdiv%3E%0D%0A%0D%0A%3Cdiv%3E%3Cstrong%3EThe+mission+of+the+Canadian+Forces+is+to%3A%3C%2Fstrong%3E%3C%2Fdiv%3E%0D%0A%0D%0A%3Cul+style%3D%22list-style-type%3A+disc%22%3E%0D%0A%09%3Cli%3Eprotect+Canada%2C%3C%2Fli%3E%0D%0A%09%3Cli%3Edefend+North+America+in+co+operation+with+the+US%2C+and%3C%2Fli%3E%0D%0A%09%3Cli%3Econtribute+to+international+peace+and+security.%3C%2Fli%3E%0D%0A%3C%2Ful%3E%0D%0A%0D%0A%3Cdiv%3E%3Cbr+%2F%3E%0D%0AOn+any+given+day%2C+about+8%2C000+Canadian+Forces+members+-+one+third+of+our+deployable+force+-+are+preparing+for%2C+engaged+in+or+returning+from+an+overseas+mission.+At+home%2C+Canadian+Forces+can+bring+the+best+available+military+resources+from+acr oss+Canada+to+bear+on+a+crisis+or+threat%2C+wherever+it+occurs%2C+nation-wide.%3Cbr+%2F%3E%0D%0A%3Cbr+%2F%3E%0D%0AThe+Canadian+Forces+now+has+an+agile%2C+high-readiness+Special+Operations+Forces+capable+of+operating+across+the+spectrum+of+conflict+at+home+and+abroad%3B+it+is+comprised+of+Joint+Task+Force+2+(JTF-2)%2C+the+Special+Operations+Aviation+Squadron%2C+the+Joint+Nuclear%2C+Biological+and+Chemical+Defence+Company%2C+and+the+Canadian+Special+Operations+Regiment.%3C%2Fdiv%3E%0D%0A&content_text_fr=%3Cdiv%3E%26nbsp%3B%3C%2Fdiv%3E%0D%0A%0D%0A%3Cdiv%3E%3Cstrong%3ELa+mission+des+Forces+canadiennes+est+de%3C%2Fstrong%3E%3C%2Fdiv%3E%0D%0A%0D%0A%3Cul%3E%0D%0A%09%3Cli%3Eprot%26eacute%3Bger+le+Canada%2C%3C%2Fli%3E%0D%0A%09%3Cli%3Ed%26eacute%3Bfendre+l%26%2339%3BAm%26eacute%3Brique+du+Nord+en+collaboration+avec+les+%26Eacute%3Btats-Unis+et%3C%2Fli%3E%0D%0A%09%3Cli%3Ede+favoriser+la+paix+et+la+s%26eacute%3Bcurit%26eacute%3B+dans+le+monde.%3C%2Fli%3E%0D%0A%3C%2Ful%3E%0D%0A%0D%0A%3Cdiv%3E%3Cbr+ %2F%3E%0D%0AChaque+jour%2C+environ+8+000+militaires+des+Forces+canadiennes+(FC)%2C+soit+%26agrave%3B+peu+pr%26egrave%3Bs+le+tiers+de+nos+forces+d%26eacute%3Bployables%2C+se+pr%26eacute%3Bparent+%26agrave%3B+une+mission+%26agrave%3B+l%26%2339%3B%26eacute%3Btranger%2C+y+participent+sur+place+ou+en+reviennent.+Au+pays%2C+les+Forces+canadiennes+peuvent+mettre+%26agrave%3B+profit+les+meilleures+ressources+militaires+de+partout+au+Canada%2C+en+cas+de+crise+ou+de+menace%2C+n%26%2339%3Bimporte+o%26ugrave%3B+sur+l%26%2339%3Bensemble+du+territoire.%3Cbr+%2F%3E%0D%0A%3Cbr+%2F%3E%0D%0ALes+Forces+canadiennes+se+sont+dot%26eacute%3Bes+d%26%2339%3Bune+capacit%26eacute%3B+d%26%2339%3Bop%26eacute%3Brations+sp%26eacute%3Bciales+%26eacute%3Blargie+et+am%26eacute%3Blior%26eacute%3Be+capables+d%26%2339%3Bintervenir+rapidement+et+pouvant+mener+des+op%26eacute%3Brations+sur+tout+l%26%2339%3B%26eacute%3Bventail+des+conflits%2C+au+Canada+comme+%26agrave%3B+l%26%2339%3B%26eacute%3Btranger+%3B+ces+forces+compren nent+la+Deuxi%26egrave%3Bme+Force+op%26eacute%3Brationnelle+interarm%26eacute%3Bes+(FOI-2)%2C+l%26%2339%3BEscadron+d%26%2339%3Bop%26eacute%3Brations+sp%26eacute%3Bciales+(Aviation)%2C+la+Compagnie+interarm%26eacute%3Bes+de+d%26eacute%3Bfense+nucl%26eacute%3Baire%2C+biologique+et+chimique+et+le+R%26eacute%3Bgiment+d%26%2339%3Bop%26eacute%3Brations+sp%26eacute%3Bciales+du+Canada.%3C%2Fdiv%3E%0D%0A

Here is my Model definition:

public class SectionContent
{
    private int _section_tab_id;
    private int _section_id;
    private string _section_name_en;
    private string _section_name_fr;
    private string _tab_title_en;
    private string _tab_title_fr;
    private int _display_order;
    private string _norm_tab_name_en;
    private string _norm_tab_name_fr;
    private string _banner;
    private bool _active;
    private int _content_id;
    private string _content_text_en;
    private string _content_text_fr;
[snip]

}

Here is my PartialView:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ForcesCMS.Models.SectionContent>" %>
<%=Html.ValidationSummary(MyLabels.labels.please_correct_markedfields, new { @class = "validation" })%>


    <fieldset>
        <legend><%=Model.tab_title_en%></legend>
        <input type="hidden" id="section_id" name="section_id" value="<%= Model.section_id%>" />
        <input type="hidden" id="section_name_en" name="section_name_en" value="<%= Model.section_name_en%>" />
        <input type="hidden" id="section_name_fr" name="section_name_fr" value="<%= Model.section_name_fr%>" />
        <input type="hidden" id="norm_tab_name_en" name="norm_tab_name_en" value="<%= Model.norm_tab_name_en%>" />
        <input type="hidden" id="norm_tab_name_fr" name="norm_tab_name_fr" value="<%= Model.norm_tab_name_fr%>" />
        <input type="hidden" id="content_id" name="content_id" value="<%= Model.content_id%>" />
        <div class="formrowFull">
            <div class="formcol">
                <label for="section_tab_id" class="inline"><%=MyLabels.labels.id%></label>
                <%= Html.TextBoxFor(model => model.section_tab_id, new { @class = "smallBoxReadonly" })%>
            </div>
            <div class="formcol">
                <label for="active" class="inline"><%=MyLabels.labels.active%></label>
                <%=Html.CheckBoxFor(model => model.active)%>
            </div>
        </div>

        <div class="formrowFull">
            <div class="formcol">
                <label for="display_order" class="inline mandatory"><%=MyLabels.labels.display_order%></label>
                <%= Html.TextBoxFor(model => model.display_order, new { @class = "smallBox" })%>
                <%= Html.ValidationMessageFor(model => model.display_order)%>
            </div>
            <div class="formcol">
                <label for="banner" class="inline"><%=MyLabels.labels.banner%></label>
                <%= Html.TextBoxFor(model => model.banner, new { @class = "largeBox" })%>
            </div>
        </div>

        <div class="formrowFull">
            <div class="formcol">
                <label for="tab_title_en" class="mandatory"><%=MyLabels.labels.title_en%></label>
                <%= Html.TextBoxFor(model => model.tab_title_en, new { @class = "largeBox" })%>
                <%= Html.ValidationMessageFor(model => model.tab_title_en)%>
            </div>
            <div class="formcol">
                <label for="tab_title_fr" class="mandatory"><%=MyLabels.labels.title_fr%></label>
                <%= Html.TextBoxFor(model => model.tab_title_fr, new { @class = "largeBox" })%>
                <%= Html.ValidationMessageFor(model => model.tab_title_fr)%>
            </div>
        </div>

        <div class="formrowFull"> 
            <div class="formcol">
                <input type="hidden" name="content_id" id="content_id" value="<%=Model.content_id %>" />
                <%= Html.LabelFor(model => model.content_text_en)%>
                <%= Html.TextAreaFor(model => model.content_text_en, new { @class = "ckeditor_tpl" })%>
                <%= Html.ValidationMessageFor(model => model.content_text_en)%>
            </div>
            <div class="formcol">
                <%= Html.LabelFor(model => model.content_text_fr)%>
                <%= Html.TextAreaFor(model => model.content_text_fr, new { @class = "ckeditor_tpl" })%>
                <%= Html.ValidationMessageFor(model => model.content_text_fr)%>
            </div>
        </div>


    </fieldset><%}%>

I'll post my Controller and script next, those are the parts that confuse me.

Controller:

[HttpGet]
    // Called when click on Edit link - data displayed in modal dialog
    public PartialViewResult AddEditRecord(int id)
    {
        ViewData["IsUpdate"] = true;
        SectionContent sc = ContentHandler.GetTabContent(id);
        return PartialView("ContentForm", sc);
    }

    [HttpPost]
    [ValidateInput(false)]
    // Called when clicking on Update in modal
    public PartialViewResult AddEditRecord(SectionContent sc, string cmd)
    {
        // Never valid because model (sc) is always null
        if (ModelState.IsValid)
        {

            try
            {
                //update
                int result = ContentHandler.UpdateSectionContent(sc);
                return PartialView("ContentForm");
            }
            catch { }

        }

        if (Request.IsAjaxRequest())
        {
            return PartialView("ContentForm", sc);
        }
        else
        {
            return PartialView("ContentForm");
        }
    }

Script:

$.ajaxSetup({ cache: false });

    function DoAjaxUpdate() {
        $.ajax({
            url: $("#frmEdit").attr("action"),
            type: 'POST',
            dataType: "json",
            contentType: 'application/json',
            data: $("#frmEdit").serialize(),
            success: function (result) {
                $('#dialog-edit').html(result);
            }
        });
    }

    $(".editDialog").live("click", function (e) {
        var url = $(this).attr('href');

        $("#dialog-edit").dialog({
            title: 'Edit Tab and Content',
            autoOpen: false,
            resizable: false,
            height: 800,
            width: 600,
            show: { effect: 'drop', direction: "up" },
            modal: true,
            draggable: true,
            open: function (event, ui) {
                $(this).load(url);
            },
            close: function (event, ui) {
                $(this).dialog('close');
            },
            buttons: {
                "Update": function () {
                    DoAjaxUpdate();
                },
                "Cancel": function () {
                    $(this).dialog('close');
                }
            }
        });

        $("#dialog-edit").dialog('open');

        return false;
    });

How do I serialize the form properly so that it is recognized as a valid ViewModel by the Controller. Then once that is settled, what should I be doing in my Controller action? JsonResult? Return PartialView? ActionResult?

I've been going through tons of SO posts and on other sites as well, I've tried a bunch of things over the last few days, but no luck. Any help appreciated. Thank you !

After correcting the error with the form tag, I finally figured out the correct jquery code to serialize my form and send it to the controller as a viewmodel.

Here is the corrected script:

function DoAjaxUpdate() {
        $.ajax({
            url: $("#frmEdit").attr("action"),
            type: "POST",
            data: $('#frmEdit :input').serialize(),
            success: function (result) {
                $('#dialog-edit').html(result);
                }
        });
    }

    $(".editDialog").live("click", function (e) {
        var url = $(this).attr('href');

        $("#dialog-edit").dialog({
            title: 'Edit Tab and Content',
            autoOpen: false,
            resizable: false,
            height: 800,
            width: 600,
            show: { effect: 'drop', direction: "up" },
            modal: true,
            draggable: true,
            open: function (event, ui) {
                $(this).load(url);
            },
            close: function (event, ui) {
                $(this).dialog('close');
            },
            buttons: {
                "Update": function () {
                    DoAjaxUpdate();
                },
                "Cancel": function () {
                    $(this).dialog('close');
                }
            }
        });

        $("#dialog-edit").dialog('open');

        return false;
    });

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