below is code snippet which return view to jquery function but i like to know how could i extract or get the view html and return to client end.
$(function(
You can make an AJAX call to the MVC action method, which will return the partial view as HTML. You then simply call the .html
jquery function to populate your div. Something like this:
$(function() {
$('#myddl').change(function() {
var url = $(this).data('url');
var value = $(this).val();
$.ajax({
type: "POST",
url: "@Url.Action("Foo", "Controller")", // replace with your actual controller and action
data: JSON.stringify({ value: value }),
success: function(result) {
$('#result').html(result);
}
});
});
You can use this method , passing the ActionResult from controller and getting back html from the view
private string RenderActionResultToString(ActionResult result)
{
// Create memory writer.
var sb = new StringBuilder();
var memWriter = new StringWriter(sb);
// Create fake http context to render the view.
var fakeResponse = new HttpResponse(memWriter);
var fakeContext = new HttpContext(System.Web.HttpContext.Current.Request,
fakeResponse);
var fakeControllerContext = new ControllerContext(
new HttpContextWrapper(fakeContext),
this.ControllerContext.RouteData,
this.ControllerContext.Controller);
var oldContext = System.Web.HttpContext.Current;
System.Web.HttpContext.Current = fakeContext;
// Render the view.
result.ExecuteResult(fakeControllerContext);
// Restore old context.
System.Web.HttpContext.Current = oldContext;
// Flush memory and return output.
memWriter.Flush();
return sb.ToString();
}
What I understand is you need a way to return raw HTML of your view to client side. If that's what you want you have to use the ViewEngine that MVC uses to render HTML.
Below is the sample :
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = null;
viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
Above code finds a partial view and converts it into HTML String by MVC view engine.
Hope this helps.