开发者

MVC 3: What's the most common way of asynchronously loading form fields based on previous choices?

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 goi开发者_如何学编程ng about this with MVC3?


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
   });
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜