Reputation: 7309
I'm writing an ASP.NET MVC 4 app. I'm relatively new to the web programming environment; I think I got the gist of the model and controller parts, including repository and unit of work patterns. But I get lost on the client side of things. Say I have this action method in my controller:
//I have a Brand table in my Entity framework model
public ActionResult GetBrands()
{
var result = _unitOfWork.BrandRepository.GetBrands();
return Json(result, JsonRequestBehavior.AllowGet);
}
I'm quite lost with Javascript, Ajax and JQueryUI. I made a static JQueryUI selectmenu in my main view (Index.cshtml):
<select name="brands" id="brands">
<option>Brand1</option>
<option>Brand2</option>
<option selected="selected">Brand3</option>
<option>Brand4</option>
<option>Brand5</option>
</select>
How can I invoke my action method to fill the select menu with the brands?
Upvotes: 0
Views: 421
Reputation: 6271
Since I don't have any idea of what the contents of "BrandRepository" is, this is a general answer.
If you're set on populating it using jquery and json, this is an example:
<script type="text/javascript">
$(function() { //only call when the DOM is ready
alert('DOM is ready!');
$.getJSON("/MyController/GetBrands/", function(result) {
alert('The controller action got hit successfully');
var options = $("#brands");
options.html(''); //clears the current options
alert('The result was: ' + JSON.stringify(result));
$.each(result, function(i, item) {
options.append('<option id="' + item.Id + '">' + item.Name '</option>');
});
});
});
</script>
This assumes that brands is composed of Id and Name in valid json.
Upvotes: 1