Reading the value of the kendoui dropdownlist

If you set the Name value of your DropDownList to match the ViewModel’s property name then it will bind directly to the ViewModel and you can just read the viewModel’s property.

In my sample the ViewModel contains an object and I want to bind to that, therefore I have  Name with a ‘.’ in it ( “Goal.GroupId”).

 

@(Html.Kendo().DropDownList()
.Name(“Goal.GroupId”)
.HtmlAttributes(new {style = “width:250px”})
.DataTextField(“Product_Group_Description”)
.DataValueField(“Product_Group_Code”)
.DataSource(source =>
{
source.Read(read =>
{
read.Action(“GetJsonGroupList”, “Goal”);
});
})
)

In the Post action that is called when the form is submitted, I can the value in 2 ways:

public ActionResult Index(FormCollection collection, Manage_GoalIndexVm vm)
{
string groupId = vm.Goal.GroupId;  // this is my preferred way
string g2 = collection[“Goal.GroupId”].ToString();  //but this is an option

return RedirectToAction(“Index”);
}

 

Kendoui dropdownlist binding to a datasource

When setting the datasource of the dropdownlist, make sure the function that provides the list returns a JsonResult. I was having issues because I was binding to a List<item> and then tried IEnumerable<item>.  I had to change the function to return a Json result version of that Ienumerable as follows:

public JsonResult GetJsonGroupList()
{
return Json(Groups, JsonRequestBehavior.AllowGet);

//Groups is  a List object
}

The razor syntax is:

@(Html.Kendo().DropDownList()
.Name(“Goal.GroupId”)
.HtmlAttributes(new {style = “width:250px”})
.DataTextField(“Product_Group_Description”)
.DataValueField(“Product_Group_Code”)
.DataSource(source =>
{
source.Read(read =>
{
read.Action(“GetJsonGroupList”, “Goal”);
});
})
)

Setting up Kendo

Even though I used the Nuget package manager to install Kendo in my web project, it didn’t work as I would expect. It failed to add a reference to the dll and it doesn’t setup the web.config files and BundleConfig.cs. It is probably a good thing it doesn’t mess with my web.config and BundleConfig.cs…. Anyway to get it running properly after running the Nuget package manager to install, you need to follow the instructions here: http://docs.kendoui.com/getting-started/using-kendo-with/aspnet-mvc/introduction

If you are working with Areas in an MVC app, then you’ll need to edit the web.config file in each area that uses the controls. If using the Razor rendering engine then you edit the web.config in the Area/Views folder by adding

 

<system.web.webPages.razor>
<host factoryType=”System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35″ />
<pages pageBaseType=”System.Web.Mvc.WebViewPage”>
<namespaces>
… (existing namespaces) ….
<add namespace=”Kendo.Mvc.UI”/>
</namespaces>
</pages>
</system.web.webPages.razor>

 

and

 

<runtime>
<assemblyBinding xmlns=”urn:schemas-microsoft-com:asm.v1″>
<dependentAssembly>
<assemblyIdentity name=”System.Web.Helpers” publicKeyToken=”31bf3856ad364e35″ />
<bindingRedirect oldVersion=”1.0.0.0-2.0.0.0″ newVersion=”2.0.0.0″ />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name=”System.Web.Mvc” publicKeyToken=”31bf3856ad364e35″ />
<bindingRedirect oldVersion=”1.0.0.0-4.0.0.0″ newVersion=”4.0.0.0″ />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name=”System.Web.WebPages” publicKeyToken=”31bf3856ad364e35″ />
<bindingRedirect oldVersion=”1.0.0.0-2.0.0.0″ newVersion=”2.0.0.0″ />
</dependentAssembly>
</assemblyBinding>
</runtime>

My process for setting up an MVC 4 web app

Create a new Project (console or web). This will create a new solution. Name the project a little differently from the Solution to prevent confusion (ie: NSFileMoveBot (solution) and NSFileMoveBot.WebUi (mvc4 project))

Add the following 3 class projects to the solution:

[SolutionName].Domain  – (will hold EF classes and enums, repository interfaces, etc)

[SolutionName].Infrastructure ( will hold repository concrete classes ).

[SolutionName].Service (will hold interfaces and concrete services which call infrastructure level classes)

-set Infrastructure to reference Domain.

-set Service to reference Infrastructure and Domain

-set console or UI to reference Service and Domain and Infrastructure

Add the following Nuget packages to each project (as needed):

– Domain -> EntityFramework 5.0

– Infrastructure -> EntityFramework 5.0

– Service -> EntityFramework 5.0  (& optionally Ninject & Ninject.Web.Common, if you setup binding function in this layer/ you can just do that in the UI layer instead)

– UI -> EntityFramework 5.0, Ninject 3.0.1.10 (or newer), (optionally Jquery, Twitter Bootstrap, FontAwesome, JqueryUI)

Setup Entities in Domain layer

1) Add new Item – Data | ADO.Net Entity Data Model (the name will determine the conn string name so name like ‘NSFileMoveBotEntities’, and on 2nd screen choose, ‘Generate From Database’ .  I generally only import the tables and views.

Setup Repository interfaces in Domain Layer, in a folder named ‘Interfaces’

1) One for each table / class  , plus

– IRepositoryBehavior.cs

– ISpecification.cs

If integrating with ActiveDirectory user account security, then create an ActiveDirectory project and add a copy of the existing Users.cs file from another copy of the class that I have previously built. I want new copies so if i change it I don’t risk breaking other applications.

Add a WebUi project (if you haven’t already). This will be an MVC4 ‘Internet application’, which is a project with an AccountController

-In the Model/AccountModel file

– comment out the ‘UsersContext’ class

– remove the [table] attribute from UserProfile

– comment out ExternalLogin class

Comment out all text in [webui]Filters | InitializeSimpleMembershipAttribute.cs (or delete the class.)

Comment (in AccountController.cs)

– //[InitializeSimpleMembership]

-//using NSFileMoveBot.WebUi.Filters;

-All functions related to ExternalLogin

in AccountController, Add

(in the class)

IAuthProvider authProvider;

public AccountController( IAuthProvider auth)

{

authProvider = auth;

}

(in the using statements)

using NSFileMoveBot.WebUI.Membership.Abstract;

-Add Ninject to this project using ‘Manage Nuget Packages’ (as you did for the other projects).

-Add Ninject.Web.Common (this adds the NinjectWebCommon class in App_Start)

-Add references to the Service and Domain projects.

-Add db conn string in web.config  like:

<add name=”NSFileMoveBotEntities” connectionString=”metadata=res://*/Entities.NSFileBotMoveEntities.csdl|res://*/Entities.NSFileBotMoveEntities.ssdl|res://*/Entities.NSFileBotMoveEntities.msl;provider=System.Data.SqlClient;provider connection string= &quot;data source=NSCxxx;initial catalog=xxx;user id=xxx;password=xxx;MultipleActiveResultSets=True;App=EntityFramework&quot;” providerName= “System.Data.EntityClient ” />

(for membership continue)

-Add to AppSetting:

<add key=”enableSimpleMembership” value= “false ” />

(if you change to .net 4.0 then you’ll need to update DotNetOpenAuth as follows)

-Use Nuget Pkg Mgr to add DotNetOpenAuth extentions for ASP.net

between

</authentication> and <pages>, add (correcting the names to match your own naming of classes)

<membership defaultProvider=”NSMembershipProvider” >

< providers>

< clear />

< add name =” NSMembershipProvider” type=”NSFileMoveBot.WebUi.Membership.Concrete.CustomMembershipProvider” />

</ providers>

</ membership>

< roleManager enabled =” true” defaultProvider= “NSRoleProvider “>

< providers>

< clear />

< add name =” NSRoleProvider” type =”NSFileMoveBot.WebUi.Membership.Concrete.CustomRoleProvider” />

</ providers>

</ roleManager>

Add WebActivatorEx using Nuget pkg manager. (already installed on my latest project by default, this allows startup code to run automatically)

Add a Ninject folder to WebUi, then add the NinjectControllerFactory.cs by copying from NSTimeEntry or other application. The complete code is:

using System;

using System.Web.Mvc;

using Ninject;

using System.Web.Routing;

namespace NSTimeEntry.WebUI.Ninject

{

public class NinjectControllerFactory: DefaultControllerFactory

{

private IKernel ninjectKernel;

public NinjectControllerFactory( IKernel kernel)

{

ninjectKernel = kernel;

}

protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)

{

return (controllerType == null) ? null : (IController)ninjectKernel.Get(controllerType);

}

}

}

If you use the default application setup, it will create the needed Membership tables in your database, but since we’re doing custome membership provider, run this script to create the membership tables:

GO

/****** Object:  Table [dbo].[webpages_Membership]    Script Date: 6/12/2013 4:35:03 PM ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE TABLE [dbo]. [webpages_Membership](

[UserId] [int] NOT NULL,

[CreateDate] [datetime] NULL,

[ConfirmationToken] [nvarchar] (128) NULL,

[IsConfirmed] [bit] NULL,

[LastPasswordFailureDate] [datetime] NULL,

[PasswordFailuresSinceLastSuccess] [int] NOT NULL,

[Password] [nvarchar] (128) NOT NULL,

[PasswordChangedDate] [datetime] NULL,

[PasswordSalt] [nvarchar] (128) NOT NULL,

[PasswordVerificationToken] [nvarchar] (128) NULL,

[PasswordVerificationTokenExpirationDate] [datetime] NULL,

PRIMARY KEY CLUSTERED

(

[UserId] ASC

)WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF , IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]

) ON [PRIMARY]

GO

ALTER TABLE [dbo]. [webpages_Membership] ADD   DEFAULT (( 0)) FOR [IsConfirmed]

GO

ALTER TABLE [dbo]. [webpages_Membership] ADD   DEFAULT (( 0)) FOR [PasswordFailuresSinceLastSuccess]

GO

GO

/****** Object:  Table [dbo].[webpages_OAuthMembership]    Script Date: 6/12/2013 4:35:17 PM ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE TABLE [dbo]. [webpages_OAuthMembership](

[Provider] [nvarchar] (30) NOT NULL,

[ProviderUserId] [nvarchar] (100) NOT NULL,

[UserId] [int] NOT NULL,

PRIMARY KEY CLUSTERED

(

[Provider] ASC ,

[ProviderUserId] ASC

)WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF , IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]

) ON [PRIMARY]

GO

GO

/****** Object:  Table [dbo].[UserProfile]    Script Date: 6/12/2013 4:35:27 PM ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE TABLE [dbo]. [UserProfile](

[UserId] [int] IDENTITY( 1,1 ) NOT NULL,

[UserName] [nvarchar] (56) NOT NULL,

[DynamicsUserId] [nvarchar] (10) NULL,

PRIMARY KEY CLUSTERED

(

[UserId] ASC

)WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF , IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY],

UNIQUE NONCLUSTERED

(

[UserName] ASC

)WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF , IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]

) ON [PRIMARY]

GO

/****** Object:  Table [dbo].[webpages_Roles]    Script Date: 6/12/2013 4:35:36 PM ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE TABLE [dbo]. [webpages_Roles](

[RoleId] [int] IDENTITY( 1,1 ) NOT NULL,

[RoleName] [nvarchar] (256) NOT NULL,

PRIMARY KEY CLUSTERED

(

[RoleId] ASC

)WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF , IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY],

UNIQUE NONCLUSTERED

(

[RoleName] ASC

)WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF , IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]

) ON [PRIMARY]

GO

GO

/****** Object:  Table [dbo].[webpages_UsersInRoles]    Script Date: 6/12/2013 4:35:42 PM ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE TABLE [dbo]. [webpages_UsersInRoles](

[UserId] [int] NOT NULL,

[RoleId] [int] NOT NULL,

PRIMARY KEY CLUSTERED

(

[UserId] ASC ,

[RoleId] ASC

)WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF , IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]

) ON [PRIMARY]

GO

ALTER TABLE [dbo]. [webpages_UsersInRoles]  WITH CHECK ADD  CONSTRAINT [fk_RoleId] FOREIGN KEY ([RoleId])

REFERENCES [dbo] .[webpages_Roles] ([RoleId])

GO

ALTER TABLE [dbo]. [webpages_UsersInRoles] CHECK CONSTRAINT [fk_RoleId]

GO

ALTER TABLE [dbo]. [webpages_UsersInRoles]  WITH CHECK ADD  CONSTRAINT [fk_UserId] FOREIGN KEY ([UserId])

REFERENCES [dbo] .[UserProfile] ([UserId])

GO

ALTER TABLE [dbo]. [webpages_UsersInRoles] CHECK CONSTRAINT [fk_UserId]

GO

GO
/****** Object: StoredProcedure [dbo].[usp_Selectwebpages_RolesByRoleName] Script Date: 02/18/2014 17:31:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[usp_Selectwebpages_RolesByRoleName]
@RoleName nvarchar(256)

As
select *
From [webpages_Roles]
Where RoleName = @RoleName