Reputation: 614
I have a ListBox in my view - when I select an item from the list box, I want to call a controller method, execute a lookup on that value, then redraw the page with those values.
My listbox code and my jQuery code looks like this:
@using (Html.BeginForm())
{
...
<h3>Environments</h3>
@Html.ListBox("Environment",
new SelectList(Model.Environments),
new {@id="environmentsListbox"})
...
}
<script>
$(document).ready(function () {
$('#environmentsListbox').click(function () {
var selected = $('#environmentsListbox').find(":selected").text();
$.ajax({
url: '@Url.Action("Index")',
data: { selectedEnvironment: selected },
success: function(data) {
---- What to do here?
}
});
});
});
</script>
The controller method looks like this:
public ActionResult Index(string selectedEnvironment)
{
// code omitted for brevity...
var frameworkConfig = GetInfo(selectedEnvironment);
return View(frameworkConfig);
}
The call works correctly, the selected text does make it to the controller method....however what do I do with the result? I'm looking for something comparable to @Html.Action("Index", selectedEnvironment)
that you would use in a normal MVC context (non-js). I have the returned View code in the data
variable, is there a way to reload the page with that value?
I've seen the answer in this post: How to call URL action in MVC with javascript function? and is very close to what I need to do, however the resulting view code from that controller method is pushed into a contained div tag, not the current view.
Upvotes: 0
Views: 1393
Reputation: 772
You can use jQuery's .html() function. Inside your success callback, do something like this:
<script>
$(document).ready(function () {
$('#environmentsListbox').click(function () {
var selected = $('#environmentsListbox').find(":selected").text();
$.ajax({
url: '@Url.Action("Index")',
data: { selectedEnvironment: selected },
success: function(data) {
$('#container').html(data);
}
});
});
});
</script>
You want to make sure that the view you are returning from your controller has the markup that you need (without any layout code etc). Access that url directly in the browser to see what it returns.
Upvotes: 1