0

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?

2 Answers 2

2

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

data: {
    id: channelId,
    updatedModel : { ...... }
},
Sign up to request clarification or add additional context in comments.

3 Comments

Do you have an example of how to send the model as data? I tried to google entity framework parse model through js code and entity framework send model through js code among other searches, but nothing useful seems to come up
I have no clue on how to express the model through JS code
Create it as a javascript object, where the properties match the names of the model on the server ie { ModelId : 1, SomeValue : 'value' }. The controller will resolve the mappings
1

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');
            }
        });
    });
}

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.