Remote modal validation attribute in ASP.NET MVC

We can use validation attribute to validate forms. Using Jquery validation plugin we can do client side validation with the help of modal validation attribute in mvc.

I have a post on client side validation.

Client Side Form validation in ASP.NET MVC

So some times we need to connect with server to validate properties. So now it is painless. We have Remote  attribute to validate such properties behind the seen.

Let’s suppose we need to validate user name property. User name should be validated with server. It can not be duplicated. So we can Use Remote validation attribute.

To validate want to connect to the server. So we can provide controller action to Remote attribute to call action and validate property behind the seen.

We can decorate property as below


[Remote("CheckUserName","Home", ErrorMessage ="User name already exists" ) ]
public string UserName { get; set; }

Modal class

usermodal

In action we should return true or false. if false returned from action error message will be shown.

Action


public JsonResult CheckUserName(string username)
{
//logic for check user name with database

return Json(false, JsonRequestBehavior.AllowGet);
}

action

My sample view contains form for enter user data


@model RemoteAttributeTestMVC.Models.User
@{
ViewBag.Title = "Home Page";
}
<div class="row" style="margin-top:10px;">
@using (Html.BeginForm("CreateUser", "Home"))
{
<div class="form-group order-form-group">
@Html.LabelFor(m => m.UserName)
@Html.EditorFor(m => m.UserName)
@Html.ValidationMessageFor(m => m.UserName)
</div>
}
</div>

This will render following form

form

To allow client side validation we have to add jquery validation plugin . I have added reference in _Layout.cshtml  as below

jval

Then run the project and when we enter values in user name text box and press tab it sends a request to CheckUserName action with parameter of user name behind the seen.

if action return false validation message will be shown in the form.

error

Download source code

Custom session store in ASP.NET MVC with Dependency Injection

In this post I will explain creating custom session helper with Unity DI.

Step 1

Create empty MVC project

Step 2

Add new folder called Utility and Add a interface with name of ISession. In a real project we can separate this logic into another project.

ISession interface


 T Get<T>(string key);
 void Set<T>(string key, T entry);

Step 3

Add a class called CustomSessionStore and implement ISession interface.

Add following logic to class.


public T Get<T>(string key)
 {
 HttpContext currentContext = GetSessionContext();

return (T)currentContext.Session[key];
 }

public void Set<T>(string key, T entry)
 {
 HttpContext currentContext = GetSessionContext();
 currentContext.Session[key] = entry;
 }
 private static HttpContext GetSessionContext()
 {
 HttpContext currentContext = HttpContext.Current;

if (currentContext == null)
 {
 throw new InvalidOperationException();
 }
 return currentContext;
 }

we have to add System.Web reference in top of page

using System.Web;

Step 4

Add Unity.MVC to project via nuget package manager

unity

Then we can see Two new classes inside App_Start folder

unityclasses

In UnityConfig.cs we can register dependecy as below.

registerTypes

Step 5

The add a controller called HomeController and implement as below

 

homecontroller

So as above we can easily set value to session using Set method. We can store any type of values since it is generic. Only thing we have to provide is type when saving and retrieving values as shown as above.

Source code

Could not load file or assembly ‘Newtonsoft.Json, Version=6.0.0.0, or one of its dependencies. The system cannot find the file specified.

Could not load file or assembly ‘Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed’ or one of its dependencies. The system cannot find the file specified.

I got this error when I added to WEB API to ASP.NET MVC project.

So This is how I get it solved

Run this command in package manager console

Update-Package –reinstall Newtonsoft.Json

 

MERGE in Sql Server

From Sql server 2012 we can merge two tables. We can map data from one table to another table. If record exists can do a update and if not insert operation can be done.

Syntax


MERGE <target_table>
USING <table_source>
ON <Search>
WHEN MATCHED THEN UPDATE SET <set_clause>
WHEN NOT MATCHED THEN INSERT VALUES (<values_list>)

Create two tables and Insert some records


CREATE TABLE TargetTable([Id] INT, [Name] NVARCHAR(50))

CREATE TABLE SourceTable([Id] INT, [Name] NVARCHAR(50))

INSERT INTO TargetTable(Id,Name)
VALUES(1, 'John'), (2, 'Mezi'), (3, 'Tom')

INSERT INTO SourceTable(Id,Name)
VALUES(1, 'JohnNew'), (4, 'Peter'), (3, 'Tom-new')

Then do Merge


MERGE TargetTable AS T
USING SourceTable AS S
ON T.Id = S.Id
WHEN MATCHED THEN UPDATE SET T.Name = S.Name
WHEN NOT MATCHED THEN INSERT VALUES (S.Id, S.Name);

Now view TargetTable Data

merge

 

CHOOSE and IIF in Sql server

CHOOSE

  • Returns a list item based on its location
  • First parameter is index
  • Next parameters are list

SELECT CHOOSE(2,'item1','item2' )
-- this will return item2

SELECT CHOOSE(1,'item1','item2' )
-- this will return item1

SELECT
CHOOSE(1,[StandardCost],[ListPrice])
FROM [Production].[Product] p
WHERE p.ProductID = 680

--this will return StandardCost

IIF

  • Instant if
  • Three parameters
    • Boolean expression
    • Return value if true
    • Return value if false

SELECT IIF([ListPrice] > 0, [ListPrice], [StandardCost]) AS 'price'
FROM [Production].[Product] p
-- if ListPrice is greater than 0 it returns Listprice. Otherwise returns StandardCost