简体   繁体   中英

Submit form from JS code

I have this form:

@model project.Models.ChannelAndLocationViewModel

@{
const string formId = "parentForm";
}

@using (Html.BeginForm("EditChannel", "Channel", FormMethod.Post, new { id = formId }))
    {
        Html.RenderPartial("EditChannelForm", Model);
        <br /><br />
        <!--<input type="submit" value="Save"/>-->

    <input type="button" value="Save" onclick="editChannel('@Model.ChannelViewModel.ID', @formId)" />

    }

I am trying to submit this form in the JS code that looks like this:

function editChannel(channelId, parentForm) {


$(parentForm).submit();

$.ajax({
    url: '/Channel/EditChannel/',
    type: "POST",
    cache: false,
    data: {
        id: channelId            
    },
    success: function (msg) {
        alert("Msg: " + msg);
        if (msg === "ChangeOfSensitiveData") {
            showAlertOnChangeOfSensitiveData('sensitivDataMsgDiv');
        } else {
            alert("Else");
        }
    },
    error: function (msg) {
        showDialog('errorDiv');
    }
});
}

But it seems that the form never gets submitted, as the model is not parsed to the controller. The model is null once the Action method is called. The action looks like this:

[HttpPost]
        public ActionResult EditChannel(int id, ChannelAndLocationViewModel updatedModel)
        { ...}

How can I submit the form from the JS file?

The model is null because it hasn't been added to the data. Try:

data: {
    id: channelId,
    updatedModel : { ...... }
},

Do it this way:

function editChannel(channelId, parentForm) {

    $("#formId").submit(function(event) {
        event.preventDefault();

        $.ajax({
            url: '/Channel/EditChannel/',
            type: "POST",
            cache: false,
            data: {
                id: channelId,
                updatedModel: parentForm
            },
            success: function (msg) {
                alert("Msg: " + msg);
                if (msg === "ChangeOfSensitiveData") {
                    showAlertOnChangeOfSensitiveData('sensitivDataMsgDiv');
                } else {
                    alert("Else");
                }
            },
            error: function (msg) {
                showDialog('errorDiv');
            }
        });
    });
}

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