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) {
}
});
return false;
});
});