I am having trouble deciding whether it is ok to construct HTML in controller actions and provide this HTML back to AJAX calls from my view (using jquery).
For instance, when selecting a client via jQuery Autocomplete, besides just getting the selected client ID we also need to construct a display or edit form for it. We might:
- Have like dozens of placeholder
div
s with proper IDs and receiveClient
JSON object from out controller action and then update those divs with the content from our object (very error prone, lots of IFs in our JS code, etc.), - or instead of requesting for a
Client
JSON object rather request the prepared HTML and just insert it into the view (more appealing solution, logic is moved into controller and easiear to maintain - I rather maintain C# code than JS).
Do you think these are valid options? What do most modern apps do?
- While 2. will work perfectly for client's display form will it work for edit for?. Eedit form should contain HTML
input
controls because I want client properties to be POSTed back because w开发者_StackOverflowhen they are posted back to the controller I can materialize a viewmodel with them.
Controller is almost never meant to do that.
Solutions are:
- Use a particular view (be it partial) to achieve this
- Send back JSON and construct tags on the client side using jquery/JavaScript
- Create a custom HTML Helper to spit out necessary tags and script.
I would personally choose 3 and then 2.
Your controller should pass data to your view, not html.
I personally would make use of PartialViews, and jQuery Load() functionality to load those partial views based on the data supplied.
Can you not just use an Ajax form for this?
i.e
1: submit the form via jquery.
2: find and return a partial view based on whatever you're passing in as a parameter.
3: update the relevant div.
精彩评论