MVC / AJAX sends data to the controller and is responsible for loading in one view

I have a page with three form fields (2 text fields, 1 drop-down list), a submit button and a Refresh link. I want to be able to click the link and transfer the values ​​of the two text fields of the form to the controller action and get a list of values ​​to populate the drop-down list. I do not want to submit the form at this stage.

At the moment, I managed to call the controller action from the link, but for some reason I can not pass two values ​​of the form field. Also, the returned JSON just takes me to a new page, rather than populating my drop-down list. Any pointers would be great as I am new to javascript and MVC. My code is below;

controller

public ActionResult Find(AddressFormViewModel model)
{
    ...
    var temp = new List<OptionModel>();
    temp.Add(new OptionModel {Id = item.Id, Value = item.desc});
    return Json(temp, JsonRequestBehavior.AllowGet);
}

HTML

@Html.TextBoxFor(x => Model.HouseNameInput, new { id = "HouseNameInput" })
@Html.TextBoxFor(x => Model.PostCodeInput, new { id = "PostCodeInput" })
@Html.ActionLink("Find","Find", "Address", new { houseInput = Model.HouseNameInput, postcodeInput = Model.PostCodeInput }, new { htmlAttributes = new { @class = "Find" } })

@Html.DropDownListFor(x => Model.AddressOption, Enumerable.Empty<System.Web.Mvc.SelectListItem>(), "-- Loading Values --", new {id = "AddressOptions"})

, , Javascript-, , ( ). .

    $(function () {
    $('.Find').click(function (evt) {
        $.ajax({
            type: 'POST',
            url: '@Url.Action("Find","AddressFormSurface")',
            cache: false,
            async: true,
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: {
                houseNameInput: $("#HouseNameInput").value,
                postCodeInput: $("#PostCodeInput").value
            },
            success: function (data) {
                if (data.exists) {
                    var ddl = $('#AddressOptions');
                    ddl.empty();

                    data.each(function () {
                        $(document.createElement('option'))
                            .attr('value', this.Id)
                            .text(this.Value)
                            .appendTo(ddl);
                    });
                }
            },
            error: function (req) {

            }
        });

        // we make sure to cancel the default action of the link
        // because we will be sending an AJAX call
        return false;
    });
});
+4
1

script, .

  • contentType: "application/json; charset=utf-8",, ( )
  • .val() (not .value),
  • exists, if, ,

, @Html.ActionLink() ( ).

<a href="#" id="find">Find</a>

script

var ddl = $('#AddressOptions'); // cache it
$('#find').click(function () { // change selector
    $.ajax({
        type: 'GET', // its a GET, not a POST
        url: '@Url.Action("Find","AddressFormSurface")', // see side note below
        cache: false,
        async: true,
        dataType: "json",
        data: {
            houseNameInput: $("#HouseNameInput").val(),
            postCodeInput: $("#PostCodeInput").val()
        },
        success: function (data) {
            if (!data) {
                // oops
                return;
            }
            ddl.empty();
            $.each(data, function(index, item) {
                $(document.createElement('option'))
                    .attr('value', item.Id)
                    .text(item.Value)
                    .appendTo(ddl);
                // or ddl.append($('<option></option>').text(item.Value).val(item.Id));
            });
        },
        error: function (req) {
            ....
        }
    }
});

. . Html.ActionLink() AddressController, script AddressFormSurfaceController

+1

Source: https://habr.com/ru/post/1608590/


All Articles