Can I use AJAX to access the html helper?

In asp.net mvc3,

I am using the javascript API to dynamically display the user interface. Part of the input section will depend on the number of elements the user wants to enter data on. As a result, something like this will not work

@(Html.EditorFor(m => m.P[5].C.Description))

as this cannot be done at runtime. What type of process would I use to invoke this helper at runtime with AJAX? Will I have a controller action that returns only the information that was called using $.ajax()? Would it be elsewhere than the action of the controller?

+3
source share
3 answers

ajax , , , , ​​/ ​​ DOM.

, JSON, :

    return new JsonResult
    {
        JsonRequestBehavior = JsonRequestBehavior.AllowGet,
        Data = new { html = this.RenderPartialViewToString("YourPartialView", model) }
    };

. :

    public static string RenderPartialViewToString(this Controller controller, string viewName = null, object model = null)
    {
        if (string.IsNullOrEmpty(viewName))
        {
            viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
        }

        controller.ViewData.Model = model;

        using (var sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
            var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
            viewResult.View.Render(viewContext, sw);
            return sw.GetStringBuilder().ToString();
        }
    }

: http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/

, , get pass, . , - :

    $.getJSON('url', numberofitems, function (data) {
        $('#somecontainer').html(data.html);
    });
+3

HTML DOM, JSON. PartialView. Html DOM

JS

$.getJSON('/someurl/GetMyView',{count:10}, function (data) {
        $('#target').html(data);
    });

:

[HttpGet]
public ActionResult GetMyView(int count)
{
  MyModel model = //Get the model from somewhere
  return PartialView(model);
}

:

@model MyModel

<div>
    @Model.SomeProperty
<div>
+1

If I understand you correctly, do you want to dynamically insert fields on the client so that users can add an N-number of fields without the presence of bazillion pre-rendered fields, and are you trying to use ajax for this?

I'm sure you could do this by providing html on the server and pushing it to the client ... do you consider adding the page dynamically to javascript? Unlike Webforms, MVC does not care about what elements were on the page when it was rendered, it only cares about the data that it receives in HttpPost.

0
source

All Articles