简体   繁体   中英

Ajax pass values from view to controller

so I'm trying to pass some values from my view to the controller, the controller gets a list and returns it.

when I try to get the values from my textboxes etc. they are all undefined... not sure what exactly I'm doing wrong here. pretty new to javascript..

here's the js code

<script type="text/javascript">
$(document).ready(function () {
    $("#getFreeApartements").on('click', function () {

        var amounta = $('#amounta').val();
        var amountc = $('#amountc').val();
        var amountan = $('#animals').val();
        var arr = $('#arrival').val();
        var dep = $('#departure').val();
        var atype = $('#atype').val();


        $.ajax({
            type: 'GET',
            data: { 'amountp': amounta, 'amountc': amountc, 'amountanimals': amountan, 'arrival': arr, 'departure': dep, 'apartmentType': atype },
            url: '@Url.Action("GetFreeApartements", "Bookings")',
            success: function (result) {
                $('freeAp').html(result);
            }
        });
        alert(amounta); // --> return undefined

    });
});

textboxinput field

    <div class="form-group">
        @Html.LabelFor(model => model.Adult, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10" id="amountp" name="amountp">
            @Html.EditorFor(model => model.Adult, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Adult, "", new { @class = "text-danger" })
        </div>
    </div>

controller:

        public ActionResult GetFreeApartements(int ap, int ac, int aa, DateTime arr, DateTime dep, ApartmentType type)
    {
 //do some stuff with received values here...
        var freeApartements = db.Apartments.ToList();
        return Json(freeApartements, JsonRequestBehavior.AllowGet);

    }

I also tried serializeArray without any success... I'm not getting any errors in the explorer console.. the function gets called, but values are null.. --> undefined should be the error.

any ideas?

So right now you have an issue with how asynchronous calls work. Your $.ajax line is going to get executed, and then right after that, the alert line will be executed - it doesn't wait for your asynchronous call to resolve before running the alert (that's the point of asynchronous calls). What you should be doing, is checking the value of amounta inside the success callback.

I modified the below to only include the relevant parts to illustrate the point. I also added the line to refetch the value of the amounta DOM element after setting the HTML:

$(document).ready(function () {
    $("#getFreeApartements").on('click', function () {

        var amounta = $('#amounta').val();

        $.ajax({
            type: 'GET',
            data: { ... data },
            url: '@Url.Action("GetFreeApartements", "Bookings")',
            success: function (result) {
                $('freeAp').html(result);
                amounta = $('#amounta').val();
                alert(amounta);
            }
        });

    });
});

You may have other issues with your controller ... but the above sample should fix your JavaScript woes you'd be seeing.

in your textboxinput code. Try using the id of the editorFor. Eg #Adult Instead of the wrapper #amountp As the id In your JavaScript

I hope this answer might help you

In the EditorFor (Text box) assign the id attribute. Assess the text box element using id in Ajax.

example

@Html.EditorFor(model => model.Adult, new { htmlAttributes = new { id="adultTextBox" @class = "form-control" } })

In the above example I have assigned the id="adultTextBox" assess it in ajax like $("#adultTextBox").val()

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