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

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.

Related

KnockoutJS getting from selection screen to edit / add screen

I am just starting to learn KnockoutJS so forgive me if this question seems silly but using an ASP MVC 3 framework how do I get information from my selection screen into my add / edit view.
Basically I have used MVCScaffold to build a basic controller for each model I have which contains an Index, Create, Edit, _CreateEdit and a couple other views. This works fine when using models because the controller creates them and passes them into my view, but now I am trying to use Knockout so I thought I was not supposed to pass a model but once in the view use a $get to grab data from the server to show on the view. That being said once I get to my edit / add screen from my selection view how do I know what record to grab using the $get function. Am I still supposed to pass some information into the model? It seems like there must be a better way than that. I am just not sure of the best practice.
Also I have an Add and Edit screen but both use the partial view of _CreateEdit so if I make my view model in the Create or Edit view how do I access this or pass it to my partial views?
Depends, are you trying to use Razor with Knockout? If so then you are in a hybrid situation where some things might come from the Razor - Model and some might come from ajax calls.
I'm guessing your $get is supposed to be $.get(). Which we would call an Ajax call
If on the other hand you want to go more pure Knockout then you would probably use a WebAPI Controller instead.
If you want to return a model from your mvc Controller that Knockout could read easily then do this:
if (this.Request.IsAjaxRequest()) return Json(model,JsonRequestBehavior.AllowGet);

How to Handle Mutiple Model Bound Forms

I am buiding a UI screen for editing the details of an Ecommerce Order. The model for my view (OrderModel) has everything I need (in properties that are also ViewModels), but the UI isn't designed to be able to edit all of it at once.
For example, one part of the UI is for customer data..another for order details, and another for tracking information, each having their own "Save" buttons.
I realize that I could use one giant form and use hidden form fields to populate the non-editable fields, making each "Save" button post all the data, but that smells bad.
I'd like to segment the editable chunks into smaller ViewModels that are posted and validated individually while retaining the strong typing but I'm unsure of how to achieve this in MVC3. Will I need partial views that are called from the primary view?
FYI, I'm using ASP.NET MVC 3 with Razor syntax and client side FluentValidation.
Partial Views are a good solution. You can pass different ViewModels to each partial view. But if only sections of the overall view are updated at a time I would not do a post back on the whole page. Instead I would use Ajax calls using JQuery/Javascript to update the individual information back to the controller. I would also look into something like Knockout.js to handle the data binding on the page.

Getting a value from an MVC 3 Razor RadioButton list

I'm coming from a WebForms environment. When I wanted values from a radiobutton, the form simply got ajax reposted or I got it thru javascript.
I've searched the web, but can't seem to find an equivalent for MVC 3 Razor.
I'm not posting the form, so I can't use the FormCollection object in the ActionResult.
I simply want to get the value of which option in the RadioButton is checked when a user checks one of them.
I assume I would do this thru an Action method in a Controller once a user checks one of the values.
Note also, that this radiobutton list is in a partial view and is available to the entire website (because it is in my _Layout.cshtml view).
Can someone please help me out with what I think should be a simple task?
You need to use javascript. See this post. MVC does not have the concept of an Auto-Postback like in Webforms. This is an optimization in the page loading time (no self-managed viewstate). This means you need to manage the statefulness of controls yourself.
In short, if you're not posting (or "getting") the form then the value won't be available in the controller...more specifically, neither the controller nor it's actions will be called at all.
If you're trying to do something strictly UI related, then you may want to consider jQuery.
If you're trying to do some sort of model validation inside of the view, you may want to reconsider your approach and usage of the MVC pattern.

ViewData in ASP.NET MVC 3

I have 2 Cotrollers.
First one sets the ViewData property like this
ViewData["Error"] = "something";
I am able display this message on the page.
Second Controller loads the grid.
When i try to set the ViewData property from that Cotroller, It does not show up on the page.
Do you why? Am I doing anything wrong here?
Please let me know.
Thanks!!!!
Using two controllers for a single view is a bit of a no-no.
Look into ViewModels to pass all of the required data to your view. You can then create a PartialView for your grid, and pass the necessary model to the Partial View as well. Consider ViewData / ViewBag a last resort when a ViewModel doesn't work.
Are you trying to use two separate controllers to render the same view? If so you should probably consider, breaking the view logic of your "grid" into a partial view that you in turn render within your primary view.
As you mentioned "ViewData" twice, another item for consideration is the implementation of the ViewModel Pattern. The Viewdata dictionary approach is fast and fairly easy to implement. however, it is not type-safe and errors due to typo's will not be caught at compile time.

MVC 3 - using reflection to choose a partial view - abuse?

I think I'm finally starting to get MVC 3, but if someone can validate this approach I'd feel better about it.
I have a website, let's say, and I have models for NormalPage and EventPage. EventPage has an EventDate, but that's the only difference, and let's just say that EventPage inherits from NormalPage if that makes life easier.
Two views handle these two (slightly) different models, one just showing the page, and the other displaying the date and showing a registration form. They have different designs, so different views are in order.
All the tutorials will say "yup, now write two Controllers: Events and Pages". That seems silly - both are just passing the model to a (appropriate) view. I can use a single "Page" controller and choose the appropriate view using reflection, right? typeof(Model), once I've pulled the data from the database, can tell me whether or not I should pull the Event view or the Page view.
Is that dumb, or asking for trouble, or misusing the framework? Thanks.
What do you intend to do with reflection? You don't need to do anything like that to return views dynamically. From any controller action, you can return View("EventView", eventModel) or View("NormalView", normalModel) and it will return that view.
On a different note, I'm not sure what tutorials suggested that it's typical to have one view per controller but it's not. It's typical to have several views and actions in one controller.

Resources