I have been struggling with this function for the past hour now and i am not sure what is going wrong, I have a function that needs to call a controller action and populate a dropdown, the code seems to fail on the line where I declare the url, it fails with undefined and throw the exception above, any idea how i can fix this, any help will be very appreciated.
Here is my dropdown definition
<div class="form-group">
@Html.LabelFor(m => m.Town, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownList("Town", ViewBag.Town as SelectList)
</div>
</div>
<div class="form-group">
@Html.Label("Surburb", new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownList("Surburb", new SelectList(string.Empty, "Value", "Text"), "Please select a Surburb", new { style = "width:250px", @class = "dropdown1" })
</div>
</div>
And here is my Jquery request
<script type="text/javascript" src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#Town").change(function () {
debugger;
var url = url("GetSurburbs", "Account");
$.post(url,{id : $("#Town").val()}).done(function(data){
alert('Success');
}).fail(function(data){
alert('failed');
});
})
})
</script>
It should be the Url.Action
html helper method.
var url = '@Url.Action("GetSurburbs", "Account")';
Assuming this code is inside a razor file.
This will execute the Url.Action
and set the return value, which is the correct relative path to the GetSurburbs
action method to the url
variable.
The above code will work when it is inside a razor file because the razor file get executed on the server. But If you do not prefer to make the html helper method calls in your js code, you can keep this url value in the view markup and read from there in your js as needed.
@Html.DropDownList("Surburb", new List<SelectListItem>(), "Please select a Surburb",
new { style = "width:250px", @class = "dropdown1",
data_url=Url.Action("GetSurburbs","Account") })
This will generate the data-url attribute to your SELECT element.Now simply read this value and use in your javascript code.
var url = $("#Surburb").data("url");
You defining url incorrectly. You need to use @Url.Action extension
<script type="text/javascript" src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#Town").change(function () {
debugger;
var url = '@Url.Action("GetSurburbs", "Account")';
$.post(url,{id : $("#Town").val()}).done(function(data){
alert('Success');
}).fail(function(data){
alert('failed');
});
})
})
</script>
User contributions licensed under CC BY-SA 3.0