Loading an EditorFor template dynamically via Ajax - ajax

I have a Model object with a List collection of sub objects. I need to load the form fields for the sub object to the page, and provide a link to dynamically add form fields for a second object. So in other words, multiple sub objects can be created via one form and one post back.
My first thought was just to put the form fields in a partial view and load the view via Ajax.ActionLink. This worked but the problem comes in when trying to uniquely identify each object in the collection and bind the collection of objects on postback. For this it seems the correct usage would be to use an #Html.EditorFor() helper, but I don't know how to call that via Ajax to dynamically add the object's editor template to the page when the link is clicked.

It sounds like you were on the right track with regards to a partial view, you'll just need to sort out the name property of your inputs so you can correctly bind to a collection of objects.
Have a look at this article by Phil Haack explaining how binding to lists works, or google for something more up to date with razor syntax.

Related

When to use MVVM (i.e. Knockout.js) or simply return an EditorTemplate object from Controller action

In cases where new items need to be added to a list via ajax, what is the biggest benefit of using something like Knockout.
So far what I have been doing is, on my view, use an editortemplate (with asscociated viewmodels) to render a list of items. Then to add a new item, I make a request to an action that loads a server-side viewmodel, and returns an EditorTemplte object which just gets appended to the list. Like this:
return Json(new { this.RenderPartialViewToString("MyEditorTemplate", model) });
The knockout way of doing things requires the implementation of another view model to display items, and then another template to display it. But doing it this way requires duplication of code since the view model has to be represented in 2 places: in the cserver side code and then the view for the knockout viewmodel. Isn't that bad practice?
Am I missing something, or understanding the purpose of knockout and MVVM?
The biggest benefit that you will see from Knockout is that you will not need to hit the server in order to add a new item to your list - everything happens client side. This has multiple benefits including:
You reduce load on your server.
You improve the end-user's experience.
You can keep multiple elements on the page up-to-date with your model without any server interactions.
Two great examples of this can be found at these Knockout tutorials:
Working with Lists and Collections
Loading and Saving Data
As far as duplicating code, if you take a look at those two tutorials, you'll notice that you don't need to duplicate code. For example:
Create a view to display your entire list.
To add a new item to the list, create a partial view that you load when you add a new item to the page - that partial view is bound to Knockout
When you submit the entire form, everything in that list will be submitted - including those items you added via Knockout.
Your ViewModel will be specific to your list item (you don't need to create an entire ViewModel for everything, necessarily). And your view is specific to a single list item.
Hope that's clear. Knockout is pretty straightforward and they have some great documentation and tutorials to help you move forward.
IMHO, the following is cleanest option for the architecture of knockout and asp mvc mixed together.
Have your ASP.net acting as a webservice and have knockout control all your view templating and logic.
Otherwise, yes there will be potential replication of viewmodels and having to refactor both front and backend code when you need to change your model.

EditorTemplate as a dynamic form

I have a form that will load some fields when the page is requested and some other fields that will be loaded as the user choses one option in a dropdown. The fields that should be loaded upon selection are EditorTemplates. Is there a way I could make it work without the need to refresh the page (i.e a partial view requested via ajax) and keeping the "binding" to my viewmodel?
Yes, this is possible as long as you respect the naming conventions of your input fields so that the default model binder can understand them. Here's an example of those conventions for lists. And here's a great article illustrating how you could implement editing a variable length list.

Using the HTML.DropDownList helper with view model and Ajax

I'm trying to use a html.dropDownList helper with a strongly typed view model with ajax. I can't the post the code because of the nature of the project.
Here basically what I'm doing...
loading a mvc view via a strongly type view model
clicking a button which does an ajax post to a controller method
using the TryUpdateModel to parse the view model
processing the request
rendering a parital view for the ajax request
According to the article listed below, the problem is that "ASP.NET MVC assumes that if you’re rendering a View in response to an HTTP POST, and you’re using the Html Helpers, then you are most likely to be 'redisplaying a form' that has failed validation."
http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx
Instead of "redisplaying the same form value", I need the html.dropDownList to be set to the same value in the view model.
Does anyone know of any custom dropDownList helpers or have any ideas of how to achieve this?
Things I've already tried/considered
per the blog, manually removing the modelstate item...didn't work - didn't pick up the value in the view model - just defaulted to the first item in dropdown list
considered just writing a regular select list...but this is sloppy and cumbersome since I'm rending multiple select lists in a loop
writing my own custom dropDownList helper...wanted to avoid reinventing the wheel
Thanks in advance
Its not fully clear to me what your problem exactly is, but I've had a similar problem. I used the Html.DropDownListFor(, SelectListItem[]) helper. At postback it sets the value to the choosen one. Your postback view doesn't require to have all the fields of the original model.
#Html.DropDownListFor(model => model.SelectedValue, MyModels.DropDownSelectables());
Here I want the selected value as the model.SelectedValue variable and within my (seperate) model I made a array of selectlistitems. The rest is automagic.
Hope it helps, D

Setting DataContext in UserControl from ViewModel

I have a View that contains a Listbox. I'll call it CityListingPage.xaml. This list page has a CityListingViewModel, that is binded with the View like somewhat like this:
DataContext="{Binding CityListing, Source={StaticResource Locator}}"
This works nicely. Now I what to change my page to a Pivot Control, where the Pivot Items, would be instances of CityListingViewModel, but obviously with different constructor data (ie. Country)
I extracted the ListBox into a UserControl. Now I'm struggling how to make this work so that for each list I get a new instance of the CityListingViewModel.
I tried creating in the ViewModelLocator a collection of CityListingViewModels but how do I pass the a CityListingViewModel instance to the UserControls DataContext?
Perhaps there is a different, better way of doing this?
Without seeing your code, I'm going to do a little guessing, but I think you can do it directly via data binding. Since each pivot item is getting an instance of CityListingViewModel, you can just pass that binding along to the UserControl:
If you post a little more code showing what you're trying to do, we might be able to be of more help.
The following are two answers for using a collection to create panorama pages. But I am quite sure that the approach can be adapted to pivot pages:
Dynamically add eventtocommand actions to a listbox
Static and dynamic panorama items in a panorama wp7 mvvm
The second post should be more relevant.
If you are thinking of partitioning the same data over multiple views on a pivot page then I would suggest NOT using several view models, especially if it is the same datasource you are using for all the data.
Simply have a parameter which each view would bind to and use Linq to control what data is visible to that parameter.
So you will have the variable which will contain all the data to be displayed and one parameter per view querying that data.

Dynamic editable table/grid generation with postback in MVC

I need to generate a table in MVC that can have a variable set of horizontal columns (years). I need to render a textbox in each cell and I need to postback the values to a action method. I have seen examples where the editable cells are generated but the columns are fixed (using partials). I have also seen examples where the table can be rendered with dynamic columns but without the editable cells/textboxes. Can anyone suggest an approach?
I would recommend creating the dynamic table with a textbox in each cell with an onchange action to send the data via ajax to the controller for the update.
You will probably need to pass a multidimensional array within the model and use it to create and load your table.
The question is though how are you expecting to handle this on the server side?
If you name them all sequentially and know the # of columns ahead of time the model binder CAN bind to a list for you if they are all named in the appropriate format. Do you want to generate the list from a model or some other method?
Phil Haack covers how the naming format is, although the EditorFor will handle this automatically in some cases. If it doesnt work in yours, simply naming them in this scheme should work.
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

Resources