In asp.net mvc3,
I am using a javascript API to dynamically render a user interface. Part of the input section is going to be dependent on how many items the user wants to enter data for. As a result, something like this wont work
@(Html.EditorFor(m => m.P[5].C.Description))
because that cannot be done during runtime. What type of process would I use to call that helper during runtime with AJAX? Would I have a controller action which only returned that information which was called using $.ajax()
? Would it be in a different place than a controller action?
At run time you could perform an ajax get to a controller action that will render a view as a string, which in turn could be inserted / appended into the DOM.
Create a new action result that returns JSON as per below:
Note, the above makes use of the following controller extension:
For further reading regarding this extension method: http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/
All that would remain would be to perform a get passing a parameter signifying the number of items to render and append the returned content into your view. Perhaps something like:
If I understand you correctly, you want to dynamically insert fields on the client to allow users to add N-number of fields without having a bazillion pre-rendered fields on the form and you are trying to use ajax to do this?
I'm sure you could do it, by rendering the html on the server and pushing it up to the client... have you considered dynamically adding the to the page via javascript? Unlike Webforms, MVC does not care what elements were on the page when it was rendered, it only cares about the data it receives in the HttpPost.
If you are pulling HTML and inserting it into the DOM, you don't have to go via JSON. Just have your action return a PartialView. It's already in the form of Html, and ready to be inserted into your DOM
JS
Controller:
View: