ASP.NET MVC 3 Partial View dynamically rendered and linked from dynamic list in view

99封情书 提交于 2019-12-05 07:00:15

问题


In my MVC 3 application, I will have a view that will contain a partial view. The view itself will have a list of dynamically generated links. The link has to cause the partial view to render detailed information for that linked item.

Would I use Ajax for this? If so, since I haven't worked with Ajax before, is there any documentation for using it in a MVC 3 app?

Also when the view is first loaded, the partial view will either not be loaded or ideally show another separate partial view. Any thoughts on a good way of doing this?

Thanks for the help.


回答1:


Create an action method which returns a PartialViewResult:

[HttpGet]
public ActionResult DetailedLinkInfo(int someIdentifier)
{
   var detailedLinkInfo = GetFromSomewhere();
   return PartialView(detailedLinkInfo );
}

Then create a partial view, strongly-typed to the type of detailedLinkInfo (let's say it's an DynamicLink.

@model WebApplication.Models.DynamicLink
@* bunch of HTML for the detailed info *@

Then use jQuery on the client-side. Give all your links a class so it makes it easier to hook up the event:

$(function() {
   $('a.dynamic-link').click(function() {
      $.get('/SomeController/DetailedLinkInfo', someIdentifier: $(this).attr('id'), function(data) {
         $('#some-div').html(data);
      });
   });
});

End result: you click one of the links, the jQuery will perform an AJAX GET to your controller action, then bind the result to the div.

HTH




回答2:


The easiest way of solving this problem that I found was using Ajax helpers that come with the MVC 3 framework. The Ajax video for MVC 3 on Pluralsight did a phenomenal job at succinctly explaining the basics of how to use this feature.



来源:https://stackoverflow.com/questions/5628611/asp-net-mvc-3-partial-view-dynamically-rendered-and-linked-from-dynamic-list-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!