Tuesday, July 30, 2013

Nested Layout pages in ASP.NET MVC

Like nested master page in ASP.NET, we can use nested layout pages in ASP.NET MVC. A layout page is a typical HTML page with a special @RenderBody() section. Here is a simple example of layout page:

<!DOCTYPE html>

<html >

<head>

    @RenderSection("styles", required: false)

</head>

<body>

    @RenderBody()

    @RenderSection("scripts", required: false)

</body>

</html> 

We can optionally define “name sections”. In the above layout page, we have define two optional name sections. Now let’s define a inner layout page:

@{

Layout = "~/Views/Shared/_Layout.cshtml";

}

@section styles {

<link href="~/Areas/Second/Content/aStyle.css" rel="stylesheet" />

}

@RenderBody()

In the above layout page, we are referring parent layout page. This inner layout page has to have a render body section. The name section is optional. You can use any of the parent name sections.

Now, we can use this nested layout page into any view.

Hope this helps!

Monday, July 29, 2013

Non-interactive Authentication to ASP.NET Web API using HTTPClient

HttpClient is a new HTTP library in .NET for accessing HTTP request. It is powerful library to utilize and get benefit of HTTP protocol. You can download it using NuGet.

In order to call authenticate service, the HTTPClient has to be authenticated with non-interactive way. On the other hand, the service has to have a login option for non-interactive client.


The following code snippet shows how we can allow non-interactive user to login:

public HttpResponseMessage PostJsonLogin(LoginModel model)
{
   if (ModelState.IsValid)
      {
       if (true)//Validate User
          {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            return Request.CreateResponse(HttpStatusCode.OK, true);
           }
       }
    return Request.CreateResponse(HttpStatusCode. Unauthorized, false);
}


Here, if the user is valid, it will pass the authentication cookie and set the HTTP status code OK.

To call any authenticate service, the HTTPClient itself has to be authenticated by calling the PosrJsonLogin action. The following pseudo code shows how we can call an authenticate action:

var cookies = new CookieContainer();
var handler = new HttpClientHandler();
handler.CookieContainer = cookies;

var client = new HttpClient(handler);
client.BaseAddress = new Uri("http://localhost:9712/baseurl ");
          

var model = new { UserName = "Gizmo", Password = "123", RememberMe = true };
HttpResponseMessage response = client.PostAsJsonAsync("api/Account/JsonLogin", model).Result;

if(response.IsSuccessStatusCode)
{
   var result = client.GetStringAsync("api/ContentManagement").Result;
}

In the above code snippet, it’s calling JsonLogin which will reply authentication cookie. If the HTTP status code is 200/OK, it can call any authenticate action.

You can download the source code from here.

Hope this helps!  

Wednesday, July 24, 2013

Automatic sign out problem in ASP.NET

Have you ever worked with two ASP.NET sites under “Default Web Site” and signing in into two sites? One of the sites gets automatically sign out. This is a silly problem I was having while showing two sites from my development machine. The problem was happening because I was using same name for “forms” tag in web.config file. Here is how we define forms authentication in web.config file:

<forms loginUrl="~/" timeout="2880" name="SameName" />

If you have two sites where name of forms tag is same, you will be sign out from one site as soon as you sign in into other site.

The solution is use different name for forms tag as long as the parent site is same.

Hope it saves your time!

Tuesday, July 23, 2013

Rich Interactive CRUD Operation In ASP.NET MVC

CRUD is fundamental operation in any application. There are many ways we can implement CRUD operation in ASP.NET MVC. If you google with bing(scott’s dialog), you will find thousands of example. However, this write-up is simple way to perform CRUD using AJAX in ASP.NET MVC. I have used the following library alone with ASP.NET MVC:

1> JQuery
2> JQuery UI
3> Bootstrapper(Not mandatory)

 You will find the source code here.

CRUD

In order to implement ajax post, I have used Ajax.BeginForm of ASP.NET MVC. The main advantage of  Ajax.BeginForm is you don’t need to do anything to submit the form as a ajax request. Moreover, it has all the default behavior of submit such as it validates the form in client side. You can use your regular form design of asp.net mvc and replace Html.BeginForm with Ajax.BeginForm.  To open the dialog, I used JQuery modal dialog.

After inserting or updating any item, we do refresh the tabular view. In my implementation, I have written a reusable javascript code to update the table. To use the reusable function, the property name has to be with table header(th) in form of  data-source="Title". Once we have property name of any particular cell, we can retrieve cell value from model. The beauty of javascript is we can get the value of any property using dot(.) operator or using key index.
Download the source code and have a look into it. It’s very simple but  powerful way to implement rich interactive CRUD operation in ASP.NET MVC. .

Hope it helps!

Monday, July 8, 2013

Show error message as tooltip in ASP.NET MVC

There are many ways form validation messages can be shown in web application. One of the typical error message is to show star(*) character beside the input box and show the actual message as a tooltip. I have been developing a web application using asp.net mvc where my clients wants to display error message as a tooltip.

In my asp.net mvc application, I am using data annotation with JQuery validation for validating my model. I will not go into the details of data annotation and JQuery validation since it is not scope of this post.

JQuery validation shows the full error message beside the input box like the following screenshot:


I didn't find any straight forward way to show error message as star(*) character. In order to achieve this, we need to write following javascript code:

$(document).ready(function () {
        var settngs = $.data($('form'), 'validator').settings;
        var oldErrorPlacement = settngs.errorPlacement;
        settngs.errorPlacement = function (error, inputElement) {
            var message = error.html();
            error.html("*");
            error.attr("title", message);
            oldErrorPlacement(error, inputElement);
        };
    });

The above code snippet overrides the errorPlacement event of JQuery validator. Inside the event, the code is self explanatory.

Now, the error message will look like following screenshot:


Hope this helps!