Sorted By: Tag (nuget)

Entity Framework DbContext Generic Repository Implementation Is Now On Nuget and GitHub

Entity Framework DbContext Generic Repository Implementation Is Now On Nuget and GitHub: PM> Install-Package GenericRepository.EF
2012-01-15 08:41
Tugberk Ugurlu


Couple of weeks ago, I have done two blog post on Generic Repository Pattern - Entity Framework, ASP.NET MVC and Unit Testing Triangle and How to Work With Generic Repositories on ASP.NET MVC and Unit Testing Them By Mocking and I have put up the https://github.com/tugberkugurlu/GenericRepoWebApp up on GitHub as well.

Now, the Generic Repository implementation has its own project separately: https://github.com/tugberkugurlu/GenericRepository. This is a simple project and has not much inside it but it is nice to have something static so that it can be improved along the way.

Here is a brief intro:

This little project contains a Generic Repository infrastructure for .NET applications and also a DbContext Implementation of that.

You can find more information about the main idea of this pattern and the usage on ASP.NET MVC along with Unit Testing by visiting the below links:

How to Install

You can directly install this little project from Nuget. There are two packages:

GenericRepository

image

Generic Repository Infrastructure For .NET Applications

GenericRepository.EF

image

Generic Repository DbContext Implementation

Releases

Under the master branch, you can find the latest stable release of this project.

Also, you can see the most up-to-date project under develop branch. Repository under develop branch is possibly the unstable version of the project.

You can also find all the releases under Tags section.

I await for your PRs :)

TinyMCE HTML Text Editior & ASP.NET MVC - Setting It Up Has Become Easy With Nuget

One of the best Javascript WYSIWYG Editors TinyMCE is now up on Nuget live feed. How to get TinyMCE through Nuget and get it working is documented in this blog post.
2011-09-07 06:15
Tugberk Ugurlu


tinymce-logoOverview of the Process

Couple of weeks ago, I was setting up a new project and I have created a folder called ‘lib’ inside the $(SolutionDir) as usual to put all the dependencies that I am going to be using for my project (.Net libraries, JavaScript libraries, etc.).

Then, I go to http://www.tinymce.com/ to grab the latest version of TinyMCE which is an awesome Javascript WYSIWYG Editor. This action popped up a balloon inside my head that tells me I had been doing this stuff over and over again for 80% of the projects that I have created. So this hits me hard and I thought I should automate this process. In order to do that, I’ve created an internal Nuget package just for myself to pull the TinyMCE package with plugins. Even, I have created EditorTemplates so that I could just give my model a hint to use the template.

That worked pretty well for me but don’t miss the point here. That worked pretty well only for me. Not for John, Denis, Adam and so on. After I thought this, I have come across a blog post about TinyMCE integration on ASP.NET MVC 3 (The blog post is in Turkish). Remember the balloon which popped up inside my head? This blog post widened that balloon and it hit me harder this time. The process which has been documented there is a very well working sample but well…, it looked more like a poor man’s TinyMCE integration for me. (The article was nice but it wasn’t following the DRY way)

After that, I have decided to enhance my packages to push them to live Nuget feed. So, I have contacted with the package admins on their forum :

TinyMCE Nuget Package

@Spocke has replied my post in a short time and gave me a go ahead to push the package to live Nuget feed. I am not going to get into details of how I created the package. Mostly, I will show how to set up your environment to get TinyMCE working in a short time.

TinyMCE into an ASP.NET MVC project

tinymce-Nuget-packages-of-mine

It is now easy to get TinyMCE package to your project with Nuget. It’s even easier to get it working with ASP.NET MVC. In this post, I am going show you the easiest way to get it work ASP.NET MVC but I hope I am going to cover for Web Forms as well in near future.

There are several packages which are related to TinyMCE that I have pushed to live Nuget feed as you can see in the picture left hand side. (This list might extend in the future) Briefly the packages are :

TinyMCE : The main package which holds the infrastructure .js files of the library and plugings. This package has no dependency at all.

TinyMCE.JQuery : Holds the JQuery integration files for TinyMCE. This package depends on TinyMCE and JQuery packages.

TinyMCE.MVC : This package holds the ASP.NET MVC EditorTemplates for TinyMCE. This package depends on TinyMCE package.

TinyMCE.MVC.JQuery : Holds the ASP.NET MVC EditorTemplates for TinyMCE.JQuery. This package depends on TinyMCE.JQuery package.

TinyMCE.MVC.Sample : Holds a sample ASP.NET MVC mini Application (it is all just a model, a controller and a view) for TinyMCE. This package depends on TinyMCE.MVC package so it uses EditorTemplates to illustrate a sample.

TinyMCE.MVC.JQuery.Sample : This package holds a sample ASP.NET MVC mini Application (it is all just a model, a controller and a view) for TinyMCE.JQuery. This package depends on TinyMCE.MVC.JQuery package so it uses EditorTemplates to illustrate a sample.

How to get TinyMCE work on and ASP.NET MVC project

I would like set the boundaries here :

  • This will demonstrate the process of integrating TinyMCE to an ASP.NET MVC application.
  • I will use the JQuery one because it has more downloads on Nuget Smile
  • I will work with the TinyMCE.JQuery.MVC package to pull down all the TinyMCE stuff along with ASP.NET MVC EditorTemplates.

Always first thing to go is File > New Project > ASP.NET MVC 3 Web Application.

In order to make it more clear, I have created a very simple BlogPost model to work with. First, I am going to show you the way without TinyMCE then later we will bring it down through Nuget.

The model looks like as below :

    public class BlogPost {

        public string Title { get; set; }
        public DateTime PostedOn { get; set; }
        public string Tags { get; set; }
        public string Content { get; set; }

    }

Then I created a controller to create a new blog post (assume here this model is related to database). The controller is simple :

using System.Web.Mvc;
using TinyMCEJQueryMVCNuget.Models;

namespace TinyMCEJQueryMVCNuget.Controllers {

    public class BlogPostController : Controller {

        public ActionResult Create() {

            return View();
        }

        [HttpPost, ActionName("Create")]
        public ActionResult Create_post(BlogPost model) {

            ViewBag.HtmlContent = model.Content;

            return View(model);
        }

    }
}

It basically does noting. Just getting the model on the http post event and pushing it back to the view with a ViewBag property.

Here is what some portion of our view looks like :

@using (Html.BeginForm()) {
    
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>BlogPost</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Title)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Title)
            @Html.ValidationMessageFor(model => model.Title)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.PostedOn)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.PostedOn)
            @Html.ValidationMessageFor(model => model.PostedOn)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Tags)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Tags)
            @Html.ValidationMessageFor(model => model.Tags)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Content)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Content)
            @Html.ValidationMessageFor(model => model.Content)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>

        <p>
            Posted Content : @ViewBag.HtmlContent
        </p>

    </fieldset>
}

When we open it up, we will see nothing fancy there :

image

When we post it, we will get this result :

image

So, we got this baby working. Let’s improve it. What we need here is to give the blogger a real blogging experience. In order to do that, we need a text editor so that we could enter our content pretty easily.

First thing is to pull down the TinyMCE.JQuery.MVC package over the wire.

install-package

When you start installing the package, your solution will have a movement so don’t freak out Smile

image

imageSo now we have our package installed, we are ready to make some changes on our model. When you go to ~/Views/Shared/EditorTemplates folder on your solution, you will see that there is a cshtml file there called tinymce_jquery_full.cshtml. This partial view enables you to view your model property with TinyMCE editor.

I am not going to go inside this file and explain how to do this (however, it is pretty simple). It is entirely an another topic.

What I would like to point out here is this : if you are working with this package (TinyMCE.JQuery.MVC), you need to have JQuery referenced on your file. We have our JQuery referenced on our _Layout.cshtml file so we do not need to do anything else.

As I got the information from the project admins, TinyMCE can work with JQuery 1.4.3 and after. You don’t need to worry about that as well. Nuget will resolve the dependency without you knowing.

Change to Our Model

To get it work, we need to change our model as follows :

using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace TinyMCEJQueryMVCNuget.Models {

    public class BlogPost {

        public string Title { get; set; }
        public DateTime PostedOn { get; set; }
        public string Tags { get; set; }

        [UIHint("tinymce_jquery_full"), AllowHtml]
        public string Content { get; set; }

    }
}

What UIHint attribute does here is to tell the framework to use tinymce_jquery_full editor template instead of the default one. AllowHtml is also there to allow html string to pass from your browser to the server. Build you project and run it again and then you should see a page similar to following one:

image

If you are unable to see this when you run your application, this can be related to several things. First thing I would do is to check if the Content property is used with EditorFor instead of another Html Helpers :

        <div class="editor-label">
            @Html.LabelFor(model => model.Content)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Content)
            @Html.ValidationMessageFor(model => model.Content)
        </div>

The second thing would be a JavaScript error related to misconfiguration or a wrong library reverence. Check your browser console for any JavaScript errors for that.

Now when we post it back to server, we will get it back as :

image

Very nice. Html has been created for us behind the scenes.

It displays it as encoded html because we didn’t specify to view as raw html. In order to do that, just use @Html.Raw.

I hope this will help you to automate some portion of your project as well.

jQuery.simpleJSlide-1.1 / Simple jQuery Slide Show Plugin With Unobtrusive JavaScript Support

An awesome and super simple jQuery slide show plugin. This plugin also takes advantage of unobtrusive JavaScript method as well.
2011-05-24 12:44
Tugberk Ugurlu


Well, the time actually came for me for both my first Nuget package and jQuery plugin : jQuery.simpleJSlide-1.1

In this blog post I am not going to go through how I created the Nuget package. Instead, I am going to explain how this small and simple slide show plugin works.

If you are interested in Nuget, there are many great learning stuff on Nuget Docs and you can also watch some basic and extreme videos on Nuget;

 http://docs.nuget.org/docs/start-here/videos

jQuery.simpleJSlide is an awesome and super simple jQuery slide show plugin. This plugin also takes advantage of unobtrusive JavaScript method as well. As I explained above, you can reach this plugin easily via Nuget;

image

Also, there is a sample package which has a basic sample example inside it. If you would like to install this package and also would like to have an example, I recommend you to install jQuery.simpleJSlide.Sample;

image

jQuery.simpleJSlide.Sample package has a dependency on jQuery.simpleJSlide package and jQuery.simpleJSlide has a dependency on jQuery and jQuery.ui.unobtrusively package. jQuery UI Unobtrusively package is a simple package which contains only one .js file that enables you to wire-up jQuery UI unobtrusively. This code iterates the page elements, finds elements with the custom attribute data-ui-fn and then apply the desired JavaScript / jQuery attribute. (Quoted from MSJoe) For Example;

<asp:TextBox runat="server" ID="startDate" data-ui-fn="datepicker" />

When you reference the proper JavaScript files (jQeury, jQuery UI and jQuery.UI.Unobtrusively) to a page, you are enabling jQeury UI Datepicker by writing above code. Yes, you are not writing one line of JavaScript code here. Very simple and clean. But what if we want to override or set some options. We’ll get to that latter but I am not going to dive into this package more in this blog post though.

image

I pushed this package into Nuget live feed but this code actually written by Damian Edwards who is a web guy at Microsoft. After I pushed the package to Nuget live feed, I told him about the package and he is now the admin of the package.

image

As I motioned, this jQuery plugin and the others can be used by this way.

Let’s look at what this plugin can give us. For the sake of simplicity I’m going to create a new ASP.NET Web Site with Visual Studio 2010;

imageimage

I’m going to fire up PMC (Package Manager Console) and install jQuery.simpleJSlide.Sample package;

image

image

As you can see, it gets bunch of things and set it up a sample for us. Your solution should look like as it is on left hand side. I made a little change on the folder structure so it doen't have look like as it is on left side. Let’s open up the index.htm file and see how the sample code looks like;

image

Don’t try to read the code. It is not the case here. Just looked at it and see if there is any JavaScript code inside the DOM. There is not. Then, let’s see what this page is doing;

 

 

As you can see it is fully functional, simple image slider with play and stop buttons. Let’s look at the code a little closer;

<div class="simpleJSlide" data-ui-fn="simpleJSlide" data-ui-simpleJSlide-actionactive="true" 
    data-ui-simpleJSlide-playbuttonid="play" data-ui-simpleJSlide-stopbuttonid="stop" data-ui-simpleJSlide-notificationactive="true">

    <h2>simpleJSlide Example Page</h2>

    <div id="mainImageContainer">
        <img alt="image" id="containerImage" src="" />
    </div>

    <div id="thumbContainer">
        <img alt="image" title="Click to See Bigger" class="thumbhotel" src="img/thumb/1.jpg" data-ui-simpleJSlide-imgSrc="img/1.jpg" />
        <img alt="image" title="Click to See Bigger" class="thumbhotel" src="img/thumb/2.jpg" data-ui-simpleJSlide-imgSrc="img/2.jpg" />
        <img alt="image" title="Click to See Bigger" class="thumbhotel" src="img/thumb/3.jpg" data-ui-simpleJSlide-imgSrc="img/3.jpg" /><br />
        <img alt="image" title="Click to See Bigger" class="thumbhotel" src="img/thumb/4.jpg" data-ui-simpleJSlide-imgSrc="img/4.jpg" />
        <img alt="image" title="Click to See Bigger" class="thumbhotel" src="img/thumb/5.jpg" data-ui-simpleJSlide-imgSrc="img/5.jpg" />
        <img alt="image" title="Click to See Bigger" class="thumbhotel" src="img/thumb/6.jpg" data-ui-simpleJSlide-imgSrc="img/6.jpg" /><br />
        <img alt="image" title="Click to See Bigger" class="thumbhotel" src="img/thumb/7.jpg" data-ui-simpleJSlide-imgSrc="img/7.jpg" />
        <img alt="image" title="Click to See Bigger" class="thumbhotel" src="img/thumb/8.jpg" data-ui-simpleJSlide-imgSrc="img/8.jpg" />
        <img alt="image" title="Click to See Bigger" class="thumbhotel" src="img/thumb/9.jpg" data-ui-simpleJSlide-imgSrc="img/9.jpg" /><br /><br />

        <span class="funcBtn" id="play">Play</span> <span class="funcBtn" id="stop">Stop</span> <span id="notificationContainer"></span>
    </div>

    <div class="clearFix"></div>

</div>

There is some conventions here;

  1. You need to specify a div element and declare data-ui-fn attribute and give it simpleJSlide as value.
  2. Inside this div element, there must be two div elements whose ids are mainImageContainer and thumbContainer.
  3. mainImageContainer div element must contain an img element whose id is containerImage and this image will be the container for your bigger sized images.
  4. Every img element inside thumbContainer div element will be recognized as a thumbnail image. There is no way to excape that for now but maybe this can be done in the future or you can do it by yourself.
  5. Every single image inside thumbContainer div element must contain data-ui-simpleJSlide-imgSrc attribute. The value of this attribute should contain bigger sized image src attribute for the particular thumbnail image as you can see above.

Also, there are some options that you can override. You can specify them by simply declaring the option name after data- ui-simpleJSlide- attribute on the div element whose data-ui-fn value is simpleJSlide. Here are the options that you can override;

  • actionactive (data- ui-simpleJSlide-actionactive) as Boolean : Specifies if the images can be iterated or not. It is set to false by default.
  • notificationactive (data- ui-simpleJSlide-notificationactive) as Boolean : Specifies if you want to display a massage after clicking play and stop buttons. It is set to false by default.
  • playbuttonid (data- ui-simpleJSlide-playbuttonid) as String : Id of the element which will start play function by clicking for iterating images. It is set to simpleJSlidePlayButton by default.
  • stopbuttonid (data- ui-simpleJSlide-stopbuttonid) as String : Id of the element which will start stop function by clicking for stopping iterating images. It is set to simpleJSlideStopButton by default.
  • notificationcontainerid (data- ui-simpleJSlide-notificationcontainerid) as String : Id of the element which will hold the notification massage for play and stop notification. It is set to notificationContainer by default.
  • playingtext (data- ui-simpleJSlide-playingtext) as String : Value of the notification massage which will be displayed for play function start. It is set to Now Playing… by default.
  • stopedtext (data- ui-simpleJSlide-stopedtext) as String : Value of the notification massage which will be displayed for stop function start. It is set to Stopped… by default.

As you see on the example, I’ve overridden some options inside the DOM.

Obtrusive and Total Lame Way

Well, if you would like to use this with JavaScript instead of this unobtrusive way, you totally can. The following code shows how the above example can be done that way;

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <title></title>
    <link href="Content/site.css" rel="stylesheet" type="text/css" />

    <script src="../Scripts/jquery-1.6.1.js" type="text/javascript"></script>
    <script src="../Scripts/jquery.simplejslide-1.1.min.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(function () {

            $("#simpleJSliderDiv").simpleJSlide({
                actionactive: true,
                playbuttonid: "play",
                stopbuttonid: "stop",
                notificationactive: true
            });

        });

    </script>

</head>

<body>

<div class="simpleJSlide" id="simpleJSliderDiv">

    <h2>simpleJSlide Example Page</h2>

    <div id="mainImageContainer">
        <img alt="image" id="containerImage" src="" />
    </div>

    <div id="thumbContainer">
        <img alt="image" title="Click to See Bigger" class="thumbhotel" src="img/thumb/1.jpg" data-ui-simpleJSlide-imgSrc="img/1.jpg" />
        <img alt="image" title="Click to See Bigger" class="thumbhotel" src="img/thumb/2.jpg" data-ui-simpleJSlide-imgSrc="img/2.jpg" />
        <img alt="image" title="Click to See Bigger" class="thumbhotel" src="img/thumb/3.jpg" data-ui-simpleJSlide-imgSrc="img/3.jpg" /><br />
        <img alt="image" title="Click to See Bigger" class="thumbhotel" src="img/thumb/4.jpg" data-ui-simpleJSlide-imgSrc="img/4.jpg" />
        <img alt="image" title="Click to See Bigger" class="thumbhotel" src="img/thumb/5.jpg" data-ui-simpleJSlide-imgSrc="img/5.jpg" />
        <img alt="image" title="Click to See Bigger" class="thumbhotel" src="img/thumb/6.jpg" data-ui-simpleJSlide-imgSrc="img/6.jpg" /><br />
        <img alt="image" title="Click to See Bigger" class="thumbhotel" src="img/thumb/7.jpg" data-ui-simpleJSlide-imgSrc="img/7.jpg" />
        <img alt="image" title="Click to See Bigger" class="thumbhotel" src="img/thumb/8.jpg" data-ui-simpleJSlide-imgSrc="img/8.jpg" />
        <img alt="image" title="Click to See Bigger" class="thumbhotel" src="img/thumb/9.jpg" data-ui-simpleJSlide-imgSrc="img/9.jpg" /><br /><br />

        <span class="funcBtn" id="play">Play</span> <span class="funcBtn" id="stop">Stop</span> <span id="notificationContainer"></span>
    </div>

    <div class="clearFix"></div>

</div>

</body>
</html>

I am not using Nuget !

Don’t worry. I have pushed the plugin to GitHub as well. Here is the project link : https://github.com/tugberkugurlu/jQuery-simpleJSlide

Enjoy Smile

How To Handle Multiple Checkboxes From Controller In ASP.NET MVC - Sample App With New Stuff After MVC 3 Tools Update

In this blog post, we will see how to handle multiple checkboxes inside a controller in ASP.NET MVC. We will demonstrate a sample in order to delete multiple records from database.
2011-04-27 11:10
Tugberk Ugurlu


checkbox

Checkboxes are so handy and easy to use. But ASP.Net MVC is a framework which stands http verbs so there is no OnClick event for buttons. Actually, there are no buttons! As you know buttons are rendered as <input value=”submit” /> native html code and .net assign some values for those input to handle them on the http post. Handling checkboxes with web forms are easy along with code behind. There is no headache there (There is no headache in MVC for me but some think that way)

But what about ASP.NET MVC? How can we handle checkboxes, which are inside a view, from controller? The solution is easier than you imagine. In this blog post, I will demonstrate a simple scenario about how to delete multiple records with the help of checkboxes.

In our sample app, I am gonna be using new things on .Net such as EFCodeFirst, EntityFramework.SqlServerCompact, MvcScaffolding. The idea is simple : we will have a simple contact form and a backend to manage those messages.

At its core, this blog post intends to show the way of handling multiple checkboxes on ASP.NET MVC but it is also a good example of how to create an ASP.NET MVC app from scratch. As you will see, we will see MvcScaffolding many times. I'll go through the basics of it but for more information, there is a blog post series on Steve Sanderson's blog:

  1. Introduction: Scaffold your ASP.NET MVC 3 project with the MvcScaffolding package
  2. Standard usage: Typical use cases and options
  3. One-to-Many Relationships
  4. Scaffolding Actions and Unit Tests
  5. Overriding the T4 templates
  6. Creating custom scaffolders
  7. Scaffolding custom collections of files

Let the code begin…

Fist thing is always first and this thing is File > New > Project on Visual Studio world. I am gonna create a new ASP.NET MVC 3 Internet Application with Razor View Engine. I am also going to create a Unit Test project related to my MVC project because I am not a bad person (on Scott Hanselman’s point of view Smile)

imageimage

BTW, Don’t worry, I am not gonna put the three circles here which explain CLEARLY what MVC framework is and blows our mindsSmile

Nuget Packages is First Thing to Go With

But before getting our hands dirty, bring up the PMC (which stands for Package Manager Console [I made it up but it might be the actual abbreviation. Open-mouthed smile If it is not, use it to make it legit!]) on Visual Studio 2010 to get the following packages;

MvcScaffolding : A fast and customizable way to add controllers, views, and other items to your ASP.NET MVC application

image

EntityFramework.SqlServerCompact : Allows SQL Server Compact 4.0 to be used with Entity Framework..

image

I am here using ASP.NET MVC 3 Tools Update so I got EntityFramework Nuget Package out of the box for support of Code First workflow for ADO.NET Entity Framework. If you are not using this update, simple install EntityFramework package from PMC or Add Library Package Reference dialog box on VS.

Now, we have built our project environment and ready to hit the code.

Be Cool and Use the PowerShell

I am no PowerShell expert. Even, I am no good at that thing. But I am enthusiastic about that and I am learning it. So in our sample project, I will use MvcScaffolding to create nearly everything that I can. I have two options here;

1 – To use GUI to scaffold my crap. This option comes with ASP.NET MVC 3 Tools Update. I am not going to be using that option.

2 – By using PMC which is a lot cooler than the GUI. I’ll be using this option along the way.

Firstly, we need our model classes. Below code includes all of model classes that we need for this small project;

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace ContactFormWithMultipleCheckboxApp.Models {

    public class Product {

        public int ProductId { get; set; }
        [Required, StringLength(50)]
        public string ProductName { get; set; }
        public string Description { get; set; }

        public virtual ICollection<Message> Messages { get; set; }

    }

    public class Message {

        public int MessageId { get; set; }
        public string From { get; set; }
        [Required]
        //below one is to validate whether the e-mail address is legit or not
        [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Email address is not valid")]
        public string Email { get; set; }
        [StringLength(100)]
        public string Subject { get; set; }
        public string Content { get; set; }

        public int ProductId { get; set; }
        public Product Product { get; set; }

    }
}

Scaffolding Controllers, Views and Repositories, DBContext (Entity Framework Code First Database Context Class)

To do so, bring up the PMC and type the following code;

image

Nice ! We have what we need so far. But not so useful. When we open up the product controller file, we will see that controller actions directly talking to Entity Framework which is not so handy in terms of Unit Testing. What can we do here. MvcScaffolding has a nice solution for that. We will just rescaffold the controller for Product class and at the same time we will create repositories. But by default, MvcScaffolding doesn’t overwrite any files that already exist. If you do want to overwrite things, you need to pass –force switch. To do so, we will do the following PS command on PMC;

image

Cool. We have our core logic for backend system. Do the same for Message class with following one line of PS code;

image

Rock on ! Perfect so far. When we fire up our app, Sql Compact database will be created for us inside our App_Data folder. Now go to the Products directory and add some products and then go to the Messages directory on the address bar.

image

There is one thing that I would like to share here. When you go to your _CreateOrEdit.cshtml file inside Views/Messages folder, you will see that the following code used for creating relational dropdownlist.

<div class="editor-field">
    @Html.DropDownListFor(model => model.ProductId, ((IEnumerable<ContactFormWithMultipleCheckboxApp.Models.Product>)ViewBag.PossibleProducts).Select(option => new SelectListItem {
        Text = Html.DisplayTextFor(_ => option).ToString(), 
        Value = option.ProductId.ToString(),
        Selected = (Model != null) && (option.ProductId == Model.ProductId)
    }), "Choose...")
    @Html.ValidationMessageFor(model => model.ProductId)
</div>

Well, this code does not work quite fine. I don’t know why and I didn’t dig into that.  I just changed the code with the following one and now it works quite well. Nevertheless, MvcScaffolding has done its part very well.

<div class="editor-field">
    @Html.DropDownListFor(model => model.ProductId, ((IEnumerable<ContactFormWithMultipleCheckboxApp.Models.Product>)ViewBag.PossibleProducts).Select(option => new SelectListItem {
        Text = option.ProductName, 
        Value = option.ProductId.ToString(),
        Selected = (Model != null) && (option.ProductId == Model.ProductId)
    }), "Choose...")
    @Html.ValidationMessageFor(model => model.ProductId)
</div>

Now, we are at the part where we should implement the logic of our core idea : deleting multiple records from the database. I have created several Messages now and our list looks like as below;

image

Hmmm, looks like Fraud has been spaming us with very old-fashioned way. Well, better delete them from database. They are garbage, right? But that’d be nice to delete them all by one click. Let’s make that happen Smile 

Open up the Index.cshtml file inside Views/Messages folder. See the change what I have done on the lines 4,5,6;

@foreach (var item in Model) {
    
    <tr>
        <td>
            <input type="checkbox" name="deleteInputs" value="@item.MessageId" />
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.MessageId }) |
            @Html.ActionLink("Details", "Details", new { id=item.MessageId }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.MessageId })
        </td>
        <td>
			@item.From
        </td>
        <td>
			@item.Email
        </td>
        <td>
			@item.Subject
        </td>
        <td>
			@item.Content
        </td>
        <td>
			@Html.DisplayTextFor(_ => item.Product.ProductName)
        </td>
    </tr>
    
}

I have added an input whose type attribute is checkbox for every generated record. So what does this think do? It enable us to catch the selected checkboxes and relate them to a record with the MessageId property. But we are not done yet. we will create a PostAction method for Index view but we are not gonna do that by typing. We will use PMC again because it’s cooler Smile Type the following;

image

Now we have our Post Action Method. The last view of this method will look like this;

        [HttpPost, ActionName("Index")]
        public ActionResult IndexPost(int[] deleteInputs) {

            var model = messageRepository.AllIncluding(message => message.Product);

            if (deleteInputs == null) {

                ModelState.AddModelError("", "None of the reconds has been selected for delete action !");
                return View(model);
            }

            foreach (var item in deleteInputs) {

                try {

                    messageRepository.Delete(item);

                } catch (Exception err) {

                    ModelState.AddModelError("", "Failed On Id " + item.ToString() + " : " + err.Message);
                    return View(model);
                }
            }

            messageRepository.Save();
            ModelState.AddModelError("", deleteInputs.Count().ToString() + " record(s) has been successfully deleted!");

            return View(model);
        }

So here what we are doing is simple. We are retrieving selected checkboxes and deleting the records from database according to MessageId property. Also, I am doing something bizarre here on the 26. I am passing the confirmation message to ModelError to view it afterwards. Probably not the smartest thing on the planet but it works for me.

Finally, add the following code to your index view page;

@using (Html.BeginForm()) {
<div>

    @Html.ValidationSummary()

</div>
<div style="float:right;">

        
        <input type="submit" value="Delete Selected Values" />
        

</div>

@*Add this below curly brace at the end of the page to close the using statement for Html.Beginform()*@
}

Fire up the project by clicking Ctrl + F5 and go to the Messages directory. You will end up with a web page which is similar to following left one. Then, select the messages which have come from Fraud who is our old-fashioned spammer. After selecting the records you would like to delete, click the button on top-right side.

imageimage

Bingo ! We are done here.

image

Of course this way is not the nicest way for this type of action. The better solution would be doing this with Ajax or JQuery post to server and removing deleted record rows with nice animation.

So why didn’t I do that here? Because I don’t have enough time for now Smile I wanna get this post up and running quickly. So, this is it for now Smile Feel free to download the source code and use it anywhere you like.

Best Solution to My Web Site With ASP.Net MVC 3 & Razor View Engine!

Recently, I have been playing around with MVC a lot and I decided to use the latest MVC tecnology on my web site...
2010-12-09 20:45
Tugberk Ugurlu


tugberk-ugurlu-com-commercial-logo-2.PNGRecently, I have been playing around with ASP.Net MVC 3.0 a lot and I decided to use the latest MVC tecnology on my web site and I have just updated my web site with MVC 3.0 and I used Razor as view engine.

I have used NuGet a lot with this project and I cannot imagine life without NuGet now :D This must be the major side affect of the NuGet, I guess :)

I have implemented lots of new features and I realized that I have improved a lot because now I consider the fact that people needs to reach the information in a very easy way. So I created tags section, archive section and internal search.

Also, I noticed that registration is lame and so I enabled comments to anyone. You do not need to log into system in order to leave a comment, just do it.

I thought that deployment would be the most annoying part since I have shared hosting (because no one is willing to support me :)) but the Visual Studio 2010 make it so easy for me with publish web site button! I just configured the publish wizard and the IDE did all the work. The hostng firm doesn't support the MVC 3 as I imagined so I need to do a little trick there. I coppied the essential dll files for MVC 3 application into my bin folder.

Ok, guys. Let's see how long I could stand up with this web site :)

Tags