ASP MVC 2 Pattern for implementing CanExecute style commands - asp.net-mvc-2

I have come from WPF (MVVM) background and trying to shift to MVC 2. Is there any pattern in MVC2 where you can use Commanding/Command buttons like <input> which you use to submit the form so that you can hide/disable when you try to Render the View.
In MVVM world, your commands could implement ICommand interface, and it had CanExecute method which was quite useful. I was wondering if there is anything similar in ASP MVC 2 ?
The only way I can think of, is to do it in the View, so that I can check the flag on ViewModel (CanSave) and depending on that show/hide the <input> tag.
Basically I want to have 2 version of the website running, one in Read-Only mode and the other Editing mode.
Let me know if you need any clarification.

ASP.NET MVC does not feature the notion of 'controls', as are found in classic ASP.NET and WPF. The foundational blocks of ASP.NET MVC are HTML elements, like <input>, <button> et cetera. Naturally, these don't offer the functionality you're looking for (i.e. Implementation of the ICommand Interface).
The scenario that you're looking at (i.e. two modes of your form) can be (and arguably should be) dealt with at the View level. You're already facing the right direction: have a 'CanSave' property on your Model, and use this in the View to determine what is generated.
Example:
<% if (Model.CanSave)
{ %>
<p>First Name: <%= Html.TextBox("firstname", Model.firstname) %> </p>
<% }
else
{ %>
<p>First Name: <%=Model.firstname %></p>
<% } %>
You'll probably want to check out the DisplayTemplates and EditorTemplates... very handy for this scenario. Brad Wilson does a good job here.
It will help you move to this:
<%= (Model.CanSave) ? Html.EditorFor(x => x.firstname) : Html.DisplayFor(x => x.firstname) %>
...which makes your View clean and nice.

If you can't get MVC to do this it's relatively worth it to hand-code something like this vb-style pseudocode. This involves...
Subclassing your controls.
Not as much of a pain as it sounds, but, it is a medium sized one. Therefore it is only appropriate for medium-sized to large apps. But worth it for them.
Interface BaseUIControl
Property Enabled as Boolean
Property Visible as Boolean
Property Name as String
Property EntireStateAsXML as string ' You can use this to do EVERYTHING!
Interface UserActionItem
Event Clicked(sender as UserActionItem ... don't pass anything from UI namespaces!)
Class MyButton (or link, etc.) Implement BaseUIControl, UserActionItem Inherits UI.Button
How does this help? You've basically replaced the missing functionality. Your Controller (or even application layer) can be aware of the UI components by interface only, so they won't have to see the UI types.
more...
You can leverage this philosophy to control everything. This has saved me thousands of hours of monkey code.
Interface TextControl
Property Value as text
Interface CheckControl
Property Checked as boolean
The above two are Pretty basic - you inherit MyCheckBox and MyTextBox from the UI versions and implement the appropriate.
Of course you could set up common code to loop thru all controls and auto-validate (or loop thru and get each one's XML to autobind the whole form).
Interface ValidationBase
Property Required as Boolean
If you have a text or numeric-only mask or restricitons built into 2 subclasses...
Interface ValidationNumeric
Property MinVal, MaxVal as double
Interface ValidationText
Property MinLen, MaxLen as double
No, it won't go to the database for you. But this sweeps a ton of crud under the rug.
You can even set these property values in the UI designer - yes, putting BL in bed with UI, BUT, if you only have one UI for the BL, actually works very well.
Now image a UI with a mix of things like listbox/multiselect, double-list picker controls, checked listbox, a groupbox of option buttons/checkboxes ...
Interface Selector
property Items as list (of string)
property SelectedItems as list (of string)
Use what works on the UI - your generic routines can care less what they look like!! The subclassed UI pieces will just implement them to set/get the right values.
In addition ... we added 'validationEquation', ActivatesEquation (gray/ungray), SetValueTriggerEquation (if true, set value to SetValueEquation, otherwise, leave alone), which allowed controls to be set to simple values from other items (basically getting the values from bound objects as if using reflection) via Pascal Gayane's Expression Evaluator (it reads .net types!)
You can also subclass the main form, have it recurse thru all it's subcontrols, put together the XML's for the whole screen, and serialize it like that. You can have your own classes implement these in the non-UI layers and use it to totally (de/)serialize the UI state, and use them to read the UI too, if they relate to a business object, to map to it.
It's unbelievable how much this simplifies a complex app. We have one with 1200+ data entry panels (... pages... ours is a thickclient app) that will fill out 250 different paper forms at 250K LOC. The form definitions contain the 'name' of each control and this is pulled from the XML generated from the screens. We probably saved 500K LOC as many of the screens have no code behind them or only trivial code; all the databinding, validation, etc. is handled by common routines that reference the interfaces.
Like I say, this only works for a big app. Spend at least 2-3 weeks developing 90% of the functionality, though; probably another month throughout the 2 years dev maturing it. I am guessing your apps is big if you're caring about ICommand and its conveniences. I would put the payback at 15-20 moderately complex pages.

If I'm understanding the question correctly, you could write a ControllerCommand class to encapsulate this. Something like this:
public class ControllerCommand
{
public string Action { get; set; }
public string Controller { get; set; }
public object RouteValues { get; set; }
public bool IsEnabled { get; set; }
}
Your Details viewmodel might use it like this:
public class DetailsModel
{
public guid Id { get; set;}
// some other viewmodel properties
public ControllerCommand Edit { get; set; }
}
You could write extension methods on HtmlHelper to replace the built-in ones:
public MvcHtmlString CommandLink(this HtmlHelper html, string linkText, ControllerCommand command, object htmlAttributes)
{
if (command.IsEnabled)
{
return html.ActionLink(linkText, command.Action, command.Controller, command.RouteValues, htmlAttributes);
}
else
{
return MvcHtmlString.Create(linkText);
// perhaps return <span class="disabled-command">linkText</span>
}
}

One of the ways I have found is to use Filter attributes which you can put in your Actions, but that only handles CanExecute on the server side.
For the GUI side, couldnt find better way than putting If statements to check if the user is Priviliged to run particular action (i.e. Edit/Delete buttons)

Related

Thymeleaf form with multiple objects of the same class

Simple problem but can't find a solution: I have a Thymeleaf form used to add a new object, say of a Book class. It works perfectly well and I only need that particular form for adding new objects, not editing the existing ones. The question is: how can I put several objects of the Book class in the same single form? So, purely for convenience, instead of filling form for a single book and clicking Send you can fill form for several books at once and only then click Send, have them all inserted into the database (in whatever order) and also have the option to fill the form partially (e.g. the form has room for 5 books but it will also accept 1, 2, 3 or 4 and you can leave the rest blank).
Edit: I've tried passing a list of object to the Thymeleaf template with the form bound to the whole list and iteration inside, but Thymeleaf throws BingingResultError upon rendering it.
You need to use a wrapper object to realize what you want.
Something like:
public class BooksCreationDto {
private List<Book> books;
// default and parameterized constructor
public void addBook(Book book) {
this.books.add(book);
}
// getter and setter
}
Then you need to pass this object as a model attribute in your controller:
BooksCreationDto booksForm = new BooksCreationDto();
model.addAttribute("form", booksForm);
bind fields using index property
th:field="*{books[__${itemStat.index}__].title}"
and get back the result with
#ModelAttribute BooksCreationDto form
in your controller.
For a complete and detailled explaination visit: https://www.baeldung.com/thymeleaf-list

Proper way to do dialogs using Prism and UWP

I'm not sure if I'm thinking about this in the correct way. I have a list of objects, and I would like the user to be able to edit and view the properties of a specified object. My initial thought is great, I'll pop up a dialog that has textboxes and let the user edit to their heart's content until they press either Ok or Cancel.
I'm on UWP, and using Prism for all of my MVVM needs. It's taken me a while, but I understand creating Views and their associated ViewModels, commands, etc. So far, I think I've done a good job keeping the view logic and business logic separated.
I've searched, but haven't found how to show a dialog in a way that follows MVVM principles. The two things that seem to be coming up the most are to use Interaction requests (which don't appear to exist using Prism on UWP), and creating a custom Content Dialog and showing it by calling ShowAsync in a method in the parent view's associated ViewModel (which seems to be counter to MVVM principles).
So, how do I either show a dialog that is defined using XAML and has an associated ViewModel (preferable since it is similar to what I'm familiar with), or another way I can tackle this problem?
Using MVVM the proper place for opening a dialog is in the ViewModel.
Usually I do something like this in your scenario:
Create an interface for showing dialogs:
public interface IWindowService
{
void OpenViewModelInWindow(ViewModelBase vm, string title, bool resizeable = true);
void CloseViewModelInWindow(ViewModelBase vm);
}
Implement this interface in UI layer:
public class WindowService : IWindowService
{
private List<Window> _windows = new List<Window>();
public void OpenViewModelInWindow(ViewModelBase vm, string title, bool resizeable = true)
{
var window = new Window
{
Title = title,
Content = vm,
Owner = Application.Current.MainWindow,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
ShowInTaskbar = false,
SizeToContent = SizeToContent.WidthAndHeight,
ResizeMode = resizeable ? ResizeMode.CanResize : ResizeMode.NoResize
};
_windows.Add(window);
window.ShowDialog();
}
public void CloseViewModelInWindow(ViewModelBase vm)
{
_windows.Single(w => w.Content == vm).Close();
}
}
In your App.xaml you need to define DataTemplates so that when you set the Content property of the window the corresponding View created in the window.
<DataTemplate DataType="{x:Type viewModel:AViewModel}">
<views:AUserControl />
</DataTemplate>
Then you can use the IWindowService from the ViewModel, you should inject it by constructor injection.
This way you are not referencing framework specific classes directly from the ViewModel. ViewModel has a reference only to an IWindowService. This has a benefit also when you want ot write unit test for a viewmodel. You can mock this service so that when the unit test is running it should not open a dialog.

How do I show a list of SmartForms in Ektron

How do I show a list of items created using a SmartForm in Ektron Version: 9.00 SP3(Build 9.0.0.249)?
I created a SmartForm where users can put in details of job positions available. Now I want to display those positions in a list i.e. jobs available. Then when they click on a link it takes them to the details of that job.
I have zero experience with Ektron so I hope this isn't a silly question and I need stuff broken down to pretty basic levels.
EDIT: You can find this and more in-depth information on using strongly typed objects with Ektron Smart Forms at Thomas Higginbotham's blog.
POST:
The example I'm creating below is for output of images in a list, as though I were going to make a gallery. Keep in mind that there are other things I would do when actually creating a gallery, so this is by no means completed code in that regard. It is, however, a very good and simple illustration for how to retrieve and handle content from Ektron in the most .NET way possible (without a lot more separation of concerns).
First, I have some recommended reading for you. Ken McAndrew (long-time Ektron dev and now Sitecore dev) put together a nice set of posts about a class you can use to obtain Ektron's Smart Form content as .NET objects, making them much easier to work with. I recommend using Ken's version of the class (link within the blog post).
There's also a hangout featuring Bill Cava, original author of the method, Ken, and myself talking about this approach, which might help.
I looked and I think the original webinar has been taken down.
Regardless, once you have the Content Types code in place, it's relatively simple. You want to:
Create .NET models for your Smart Forms
Get the items
Map them to a ViewModel (optional)
Databind them to a ListView or Repeater control
Creating .NET Models for Smart Forms
To start this, I've created a rather simple Smart Form for a Press Photo. It contains three fields:
Name
Description (Caption)
Image (stored as a URL string for simplicity, not as an <img /> tag)
Next, click the "XSD" button in the SmartForm Data Design View (where you add/manage the fields) and copy all the XSD code. (You'll see the XSD button in the screenshot below, immediately above the modal.)
Save that to a file. I created a folder at C:\ContentTypes and added the file as PressPhoto.xsd there.
You'll want to run a file called XSD.exe (provided and documented by Microsoft as part of most Visual Studio installations). This will use the XSD and generate a C# class file for you - one that's friendly for deserializing the Smart Form XML into a .NET object.
Here's where to find it (as included with Visual Studio 2015):
However, running it from the command line is something I find painful since I always forget the rather lengthy path for it. So I created a Batch file to do most of the dirty work for me. I wrote it to accept three parameters, in order:
The path to the XSD file
The output path where I'd like to store the generated class file
The namespace I want for the generated class (tip: I always set the Namespace to include the name of the Smart Form - this prevents conflicts if you're generating classes for multiple Smart Forms)
Here's the code and a screenshot of the command to execute it.
#ECHO OFF
SET xsdExePath="C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\xsd.exe"
SET xsdFilePath="%~f1"
SET outFolderPath="%~f2"
SET ns=%3
%xsdExePath% /c %xsdFilePath% /o:%outFilePath% /l:CS /n:%ns%
This generates a file named PressPhoto.cs within my C:\ContentTypes\ directory.
Going into my Ektron project, I'm going to add Ken's SmartForm class (referenced in his blog above) and my new PressPhoto class within a directory in my App_Code folder. Like so (folder structure beneath App_Code/CSCode is up to you, but keep it organized for your own sanity):
Add a class for each Smart Form you want to pull via API (for me, that's all Smart Forms).
I know this is seemingly a lot of prep, and compared to some other, more modern systems, it is. But this will help you immensely once you're in the habit.
Get the Items (and Map to a ViewModel)
Now that you've basically created your own APIs for getting the items (the alternative is XML Transforms, btw), you're ready to use them.
I prefer to create my own "Manager" class as well as ViewModel. If you'd prefer a different approach, then this will at least give you the sample code to move in your own direction.
I'm putting comments about the code in-line so you can read them in context.
View Model - very basic
namespace MyProject.ViewModels
{
/// <summary>
/// Provides the fields necessary to display a PressPhoto Smart Form to the site.
/// </summary>
public class PressPhotoViewModel
{
public string Title { get; set; }
public string Description { get; set; }
public string ImageUrl { get; set; }
public string ContentUrl { get; set; }
public long ContentId { get; set; }
public PressPhotoViewModel()
{
}
}
}
And the "Manager" class so I put as little code into the code-behinds as possible. A nice, centralized location for all my PressPhoto logic.
using Ektron.Cms;
using Ektron.Cms.Content;
using Ektron.Cms.Common;
using Ektron.Cms.Framework.Custom;
using MyProject.SmartForms.PressPhoto;
using MyProject.ViewModels;
using System.Collections.Generic;
using System.Linq;
namespace MyProject.Managers
{
/// <summary>
/// Provides CRUD operations for managing PressPhoto objects within the CMS.
/// </summary>
public class PressPhotoManager
{
/*
* "root" is the default root element of the Smart Form XML.
*
* If you've changed this, your code will be different. Most people don't,
* so I'm going with the lowest-common-denominator example.
*
* I normally set the "root" to something else, and thus give it a more
* meaningful class name. I also tend to load this manager via something more
* similar to a singleton, but for simplicity's sake...
*/
private SmartFormManager<root> pressPhotoManager = new SmartFormManager<root>();
public PressPhotoManager()
{
// Nothing needs done here for this example.
}
/*
* Usually, I'm not interested in writing information back to the DB, so
* I'm only going to include samples for GetItem and GetList (by folder) here.
*/
/// <summary>
/// Retrieves a PressPhoto item by its Ektron Content ID
/// </summary>
/// <param name="ContentId">Ektron Smart Form Content Id</param>
/// <returns>Press Photo ViewModel for display</returns>
public PressPhotoViewModel GetItem(long ContentId)
{
/*
* Get items - this returns an object that is the amalgamation of the standard
* Ektron ContentData object and the deserialized Smart Form information.
*
* The format is:
* * systemObject.Content = standard ContentData fields
* * systemOjbect.SmartForm = Smart Form fields
*
* For some reason, the returned object in the custom class inherits from ContentData.
* This inheritance is probably not necessary and is also likely confusing. So only try
* to use the fields within the containers listed above.
*/
var systemObject = pressPhotoManager.GetItem(ContentId, false);
if (systemObject == null) return null;
/*
* I often want to map both Smart Form and ContentData fields to my output. This is where
* a ViewModel comes in handy - it normalizes the data to be rendered. So then I'm not
* dealing with object.Content.* and object.SmartForm.* during rendering.
*
* Another note: You might consider putting this mapping into a constructor in
* the ViewModel in order to avoid the repetition you'll find in the GetList method
* below.
*/
return new PressPhotoViewModel()
{
ContentId = systemObject.Content.Id,
ContentUrl = systemObject.Content.Quicklink,
Title = systemObject.SmartForm.Name,
Description = systemObject.SmartForm.Caption,
ImageUrl = systemObject.SmartForm.Photo
};
}
/// <summary>
/// Retrieves a list of PressPhoto by the containing Ektron Folder Id (non-recursive)
/// </summary>
/// <param name="FolderId">Ektron Folder Id</param>
/// <returns>Enumerable of Press Photo ViewModel for display</returns>
public IEnumerable<PressPhotoViewModel> GetList(long FolderId)
{
/*
* There are several "Criteria" objects. This is the simplist, but they also exist
* for retrieving items from a Collection, from Taxonomy, or given a certain
* Metadata property value.
*/
var criteria = new ContentCriteria();
// Filter tells the API which folder to retrieve content from.
criteria.AddFilter(ContentProperty.FolderId, CriteriaFilterOperator.EqualTo, FolderId);
// Don't check sub-folders.
criteria.FolderRecursive = false;
/*
* Retrieve only 12. The default is 50. Get in the habit of setting this so you
* don't grab 50 when you only need one.
*/
criteria.PagingInfo = new PagingInfo(12);
// Only return metadata when you need it, for performance. Default here is false.
criteria.ReturnMetadata = false;
// Ordering FTW! Hopefully self-explanatory.
criteria.OrderByField = ContentProperty.Title;
criteria.OrderByDirection = EkEnumeration.OrderByDirection.Ascending;
// Same as above...
var systemObjectList = pressPhotoManager.GetList(criteria);
if (systemObjectList == null || !systemObjectList.Any()) return null;
return systemObjectList.Select(p => new PressPhotoViewModel()
{
ContentId = p.Content.Id,
ContentUrl = p.Content.Quicklink,
Title = p.SmartForm.Name,
Description = p.SmartForm.Caption,
ImageUrl = p.SmartForm.Photo
});
}
}
}
Databinding to a List Control
For simplicity, I'm going to put this code into a .NET User Control.
Markup:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="Gallery.ascx.cs" Inherits="Components_Controls_Gallery" %>
<asp:ListView ID="uxPhotoGallery" runat="server" ItemPlaceholderID="itemPlaceholder">
<LayoutTemplate>
<ul>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li>
<%--
I'm mixing up two different ways of referencing the incoming data. One is by casting
the DataItem to the incoming type, which gives you intellisense access to the properties.
The other is more of a dictionary approach in which you have to type out the property name
as a string.
I really like the casting approach, but it's mega-wordy.
--%>
<a href="<%#((MyProject.ViewModels.PressPhotoViewModel)Container.DataItem).ImageUrl %>">
<img src="<%#((MyProject.ViewModels.PressPhotoViewModel)Container.DataItem).ImageUrl %>" alt="<%#Eval("Description") %>" />
<div><%#Eval("Description") %></div>
</a>
</li>
</ItemTemplate>
</asp:ListView>
Code:
using MyProject.Managers;
using System;
using System.Linq;
public partial class Components_Controls_Gallery : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
var pressPhotoManager = new PressPhotoManager();
// Whichever folder Id...
var photos = pressPhotoManager.GetList(75);
if (photos != null && photos.Any())
{
uxPhotoGallery.DataSource = photos;
uxPhotoGallery.DataBind();
}
}
}
And... that should do it. The best way I know how, in any case. There are certainly ways that require less code and prep, but this is by far my preferred as it keeps me working as much as possible with real .NET objects. Though you could use LinqToXML or other techniques, I prefer to not use them as it requires you to develop a lot of your own knowledge of the XML and never reads as well as this, imo.
Happy coding.

How do I avoid repetition when passing variables from the Controller/Action to the Layout

I am currently working on a project developed using Zend Framework, based on the structure of my web page design I have reached a point where I have to pass a small number of variables to my layout from each Controller/Action. These variables are:
<?php Zend_Layout::getMvcInstance()->assign('pageId', 'page1'); ?>
<?php Zend_Layout::getMvcInstance()->assign('headerType', '<header id="index">'); ?>
The reason for passing this information is firstly, I pass the page id as the multi column layout may change depending on the content being displayed, thus the page id within the body tag links the appropriate CSS to how the page should be displayed. Secondly I display a promotional jQuery slider only on the index page, but I need the flexibility to have it displayed on potentially multiple pages in case the wind changes and the client changes their mind.
My actual question: Is there a more appropriate method of passing this information to the Layout that I am overlooking?
I am not really questioning whether the information has to be sent, rather is there some Zend Framework feature that I have, in my haste, overlooked which would reduce the amount of repetitive redundant code which may very well be repeated in multiple Actions within the same controller?
You could turn that logic into an action helper than you can call from your controllers in a more direct way. You could also make a view helper to accomplish the same thing but view helpers usually generate data for the view rather than set properties.
// library/PageId.php
class Lib_PageId extends Zend_Controller_Action_Helper_Abstract
{
public function direct($title, $pageId, $headerType)
{
$view = $this->getActionController()->view;
$view->headTitle()->append($title);
$view->pageId = $pageId;
$view->headerType = $headerType;
}
}
In your controller actions you can now do this:
$this->_helper->PageId('Homepage', 'page1', 'index');
// now pageId and headerType are available in the view and
// Homepage has been appended to the title
You will also need to register the helper path in your Bootstrap like this:
protected function _initActionHelpers()
{
Zend_Controller_Action_HelperBroker::addPrefix('Lib');
}
Doing it like that can reduce the amount of repetitive code and remove needing to assign the values from the view. You can do it in the controller very quickly. You can also have default values in the case that the helper hasn't been called.
You shoudn't really be passing anything from the view to the layout, for a start the view should be included IN the layout, not the other way around.
So, setting your page title should be done using similar code to what you have, but inside the controller action being called:
$this->view->headTitle()->append('Homepage');
And the other two issues - you need to rethink as I stated to begin with. Maybe you're misunderstanding the layout/view principle? If you include the different views per action, then you simply change the div id when needed, and include the header for your banner only in the index.phtml file.

Binding two objects of the same type in an action

I have a page that collects information on two objects of the same type. When the page is submitted the action that handles the processing of the information submitted is attempting to use model binding, something similar to:
public ActionResult Submit(Person parent, Person child)
{
//Do some stuff
}
It manages to bind one of them successfully but not the other. Does anyone have any suggestions/resources etc that could help me get this to work?
If needed I can gut/rename and post the actual code for the various pieces.
The solution to this is very much similar to the solution to my question that I posted the other day (I wouldn't at all call this a dupe though).
What you need to do is just include the parameter name in your inputs, eg:
<%: Html.TextBox("Parent.Name") %>
.....
<%: Html.TextBox("Child.Name") %>
and it should all automagically work.
(I think this is MVC2 only, you didn't mention whether you were using 1 or 2)
Would it make sense to have a ParentChild Model with two person instances in it?
I don't think I've seen any examples like this trying to bind two models on post.