user1140479
user1140479

Reputation:

Ajax.BeginForm onBegin does not set values

Maybe this is a stupid question, but I haven't found it out ... yet.

I have a view in MVC with an Ajax.BeginForm. The model has a property Value (string). This is a part of the view:

@using (Ajax.BeginForm("Edit", "TheController", new AjaxOptions {
    UpdateTargetId = "Target",
    InsertionMode = InsertionMode.Replace,
    LoadingElementId = "loader",
    OnBegin = "SetValues()"
})) {
    @Html.HiddenFor(x => x.Value)

    <label>A label</label>
    <input type="text" id="anInt"/>
    <select id="aMeasurement">
        <option value="px">PX</option>
        <option value="%">%</option>
        <option value="em">em</option>
    </select>

    <input type="submit" id="submitButton" value="Submit it"/>
}

The function SetValues:

function SetValues(){
    $("#Value").val($("#anInt").val() + $("#aMeasurement").val())
}

This should set, for example, 100px in the hiddenfield "Value".

When submitting the forum, I expect the field "Value" to become a combination of anInt and aMeasurement, but it isn't. I use Chrome and when I inspect the elements I see the correct value set in the hidden element "Value", but when I debug the controller, the Value is empty.

When I debug the JS I see that the function SetValues is called and I also see the correct value is set in the Value-element. After the JS function is completed Visual Studio breaks on the the breakpoint on the correct method in the controller.

I cannot seem to figure out why this isn't working. Or maybe I'm dealing with this the wrong way.

Anyone knows how to do this or has a better idea?

UPDATE

Thanks to ryanulit and Scott MacMaster, I came up with this:

I added an ID to the form and added this little JS script:

$(function(){
    $("ID_OR_NAME_FORM").submit(function () {
        ... Do stuff
    });
});

As soon as the form is submitted (and before sending data to the controller) the submit-function in Javascript is called. This will set the correct values for me and then post data to the controller.

Upvotes: 4

Views: 3013

Answers (2)

Mateusz
Mateusz

Reputation: 116

My solution for this problem is very simple:

$("#Form_Id_You_Have_To_Change").on("submit", function () { SetValues(); });

Upvotes: 2

Skye MacMaster
Skye MacMaster

Reputation: 914

I think you meant this

function SetValues(){
    $("#Value").val($("#anInt").val() + $("#aMeasurement").val())
}

Upvotes: 0

Related Questions