0

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.

4

1 に答える 1

1

jQuery の .html() 関数を使用できます。成功のコールバック内で、次のようにします。

<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>

コントローラーから返されるビューに必要なマークアップがあることを確認する必要があります (レイアウト コードなどは必要ありません)。ブラウザーでその URL に直接アクセスして、返される内容を確認します。

于 2013-04-15T15:08:26.887 に答える