4

Imagine having two list boxes on a form, where the choices in the second depend on what's been picked in the first. What's the most common, or cleanest way of going about this with MVC3?

ShawnL
  • 97
  • 3

2 Answers2

2

I would say that you would need two things to accomplish this cleanly; Ajax and a Json ActionResult

$('#listbox').change(function() {
  $.ajax({
    url: '/ListBoxChange',
    method: 'POST',
    data: {
      listBoxValue: 'The value'
    },
    success: function(data) {
      alert (data.Result);
    }
  });
});

The Action Result:

[HttpPost]
public ActionResult ListBoxChange(string listBoxValue)
{
   string result = GetResult();
   return Json(new {
     Result = result
   });
}
Mike Richards
  • 5,557
  • 3
  • 28
  • 34
0

Alternatively can use the MVC framework, directly binding back to view after a partial refresh. I've used the following for complex dynamic searches, works decently.

<script src="<%= Url.Content("~/Scripts/MicrosoftAjax.js") %>" type="text/javascript"></script>
 <script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.js") %>" type="text/javascript"></script>

    <% using (Ajax.BeginForm("/GetProducts",
        new AjaxOptions()
        {
            InsertionMode = InsertionMode.Replace,
            HttpMethod = "POST",
            OnBegin = "beginSearchLoader",
            OnComplete = "completeSearchLoader",
            UpdateTargetId = "divSelectionResult"
        }
    ))
 { %>

            <div id="divSelectionResult">
                <% Html.RenderPartial(Html.ProductViewPath("ProductContainer") , Model); %>
            </div>



    public ActionResult GetProducts(FormCollection form)
    {
      //search parameters used in Form 
      ProductModel modelData = Search(form); 
      ViewData.Model = modelData; 

      //AJAX Partial View Return
      return PartialView(Constants.VIEW_FOLDER + "ProductContainer" + Constants.PARTIALVIEW_EXTENSION);
    }

FYI: Some of the code is using custom helpers and etc.

Nickz
  • 1,880
  • 17
  • 35