Thursday 26 December 2013

RenderPartial vs RenderAction vs Partial vs Action in MVC Razor

There are different ways for rendering a partial view in MVC Razor. Many developers got confused whether to use RenderPartial or RenderAction or Partial or Action helper methods for rendering a partial view. In this article, I would like to expose the difference among Html.RenderPartial, Html.RenderAction, Html.Partial & Html.Action.

Html.RenderPartial
  1. This method result will be directly written to the HTTP response stream means it used the same TextWriter object as used in the current webpage/template.
  2. This method returns void.
  3. Simple to use and no need to create any action.
  4. RenderPartial method is useful used when the displaying data in the partial view is already in the corresponding view model.For example : In a blog to show comments of an article, we would like to use RenderPartial method since an article information with comments are already populated in the view model.
  5. This method is faster than Partial method since its result is directly written to the response stream which makes it fast.
@{Html.RenderPartial("_Comments");}

Html.RenderAction
  1. This method result will be directly written to the HTTP response stream means it used the same TextWriter object as used in the current webpage/template.
  2. For this method, we need to create a child action for the rendering the partial view.
  3. RenderAction method is useful when the displaying data in the partial view is independent from corresponding view model.For example : In a blog to show category list on each and every page, we would like to use RenderAction method since the list of category is populated by the different model.
  4. This method is the best choice when you want to cache a partial view.
  5. This method is faster than Action method since its result is directly written to the HTTP response stream which makes it fast.
@{Html.RenderAction("Category","Home");} 

Html.Partial
  1. Renders the partial view as an HTML-encoded string.
  2. This method result can be stored in a variable, since it returns string type value.
  3. Simple to use and no need to create any action.
  4. Partial method is useful used when the displaying data in the partial view is already in the corresponding view model.For example : In a blog to show comments of an article, we would like to use RenderPartial method since an article information with comments are already populated in the view model.
@Html.Partial("_Comments")

Html.Action
  1. Renders the partial view as an HtmlString .
  2. For this method, we need to create a child action for the rendering the partial view.
  3. This method result can be stored in a variable, since it returns string type value.
  4. Action method is useful when the displaying data in the partial view is independent from corresponding view model.For example : In a blog to show category list on each and every page, we would like to use Action method since the list of category is populated by the different model.
  5. This method is also the best choice when you want to cache a partial view.
@{Html.Action("Category","Home");} 


Continue Reading →

Monday 16 December 2013

RenderBody, RenderPage and RenderSection methods in MVC 3

In this article we will learn about the three methods of MVC 3 and those are RenderBodyRenderPage, andRenderSection. We will learn by the following topics:
  • RenderBody
    • What is RenderBody?
    • How RenderBodyworks?
    • RenderBody Example
  • RenderPage
    • What is RenderPage?
    • How RenderPageworks?
    • RenderPage example
  • RenderSection
    • What is RenderPage?
    • How RenderPageworks?
    • RenderPage Example
Now go to in detail…

RenderBody

What is RenderBody?
In layout pages, renders the portion of a content page that is not within a named section. [MSDN]
How RenderBody works (graphical presentation)?


RenderBody Example
It’s simple. Just create a ASP.NET MVC 3 web application by visual studio 2010. After creating this application, you will see that some files and folders are created by default. After that open the _layout.cshtml file from views/Sharedfolder.  Basically this file will be used as a standard layout for all the page in project. Keep in mind that you can create more then one layout page in a application and to use layout page in other page is optional. The _layout.cshtml file consist the following code.

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
</head>
<body>
    <div class="page">
        <div id="header">
            <div id="title">
                <h1>My MVC Application</h1>
            </div>
            <div id="logindisplay">
                @Html.Partial("_LogOnPartial")
            </div>
            <div id="menucontainer">
                <ul id="menu">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                </ul>
            </div>
        </div>
        <div id="main">
            @RenderBody()
        </div>
        <div id="footer">
        </div>
    </div>
</body>
</html>

Now open another file called index.cshtml from views/home. This file consists of the following code:

@{
    ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>

Main thing is that by the above code you couldn’t find which layout page is being used by this index page. But there is little tricks done at MVC3. You will get a file called _ViewStart.cshtml at views folder. This file consist of  following code.

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

This code means that by default all the content pages will follow the _Layout.cshtml layout page.  Now if we consolidate the _layout.cshtml and index.cshtml page both, we will get the following code.

<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
</head>
<body>
<div class="page">
<div id="header">
<div id="title">
<h1>My MVC Application</h1>
</div>
<div id="logindisplay">
@Html.Partial("_LogOnPartial")
</div>
<div id="menucontainer">
<ul id="menu">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
</ul>
</div>
</div>
<div id="main"><h2>@ViewBag.Message</h2>
<p>
To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>
</div>
<div id="footer">
</div>
</div>
</body>
</html>

It’s nothing complicated, it’s just replacing the code of RenderBody() of layout page by the code of content page.
if you want to use different layout for different content pages, then create a layout page as like _Layout.cshtml and just copy below code to your desired content page.

@{
  Layout = "another layout page";
}

RenderPage

What is RenderPage?
Renders the content of one page within another page. [MSDN] The page where you will place the content could be layout or normal page.
How RenderPage Works (graphical presentation)?


RenderPage Example
Create a page called _StaticRenderPage at Views/Shared folder. Open it and paste the below code.

<p>
This messge from render page.
</p>

Open the Index.cshtml file from Views/Home folder and paste the below code.

@RenderPage("~/Views/Shared/_StaticRenderPage.cshtml")

Now If you merge the code of _StaticRenderPage to Index.cshtml, then you will get the below code.

@{
    ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>
<p>
This messge from render page.
</p>

If you want to pass the data by using RenderPage, then you have to use the data parameter at RenderPage. I will give another example for this. To do this, at first create a class file called AvailableUser at Models/AccountModels. Create the class with the below code.

    public class AvailableUser
    {
        public string UserName { get; set; }
        public string UserPassword { get; set; }

        public static List<AvailableUser> AllUsers()
        {
            List<AvailableUser> userList = new List<AvailableUser>();

            AvailableUser user1 = new AvailableUser
            {
                UserName = "Anupam Das",
                UserPassword = "lifeisbeautiful",
            };

            AvailableUser user2 = new AvailableUser
            {
                UserName = "Chinmoy Das",
                UserPassword = "GoodTime",
            };

            userList.Add(user1);
            userList.Add(user2);

            return userList;
        }
    }

Now go to AccountController and write down the below code
public ActionResult AvailableUserList()
{
return View(MvcApplication1.Models.AvailableUser.AllUsers());
}

Create a view page called AvailableUserList.cshtml at Views/Account with the below code

@model IEnumerable<MvcApplication1.Models.AvailableUser>

@{
ViewBag.Title = "AvailableUserList";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>AvailableUserList</h2>

@RenderPage("~/Views/Shared/_DisplayAllUsers.cshtml", new { AvailableUser = Model })

At last create another view page called _DisplayAllUsers at Views/Shared with the below code.

@foreach (var usr in Page.AvailableUser)
{
<text>
@usr.UserName   @usr.UserPassword <br />
</text>
}

Now run the project (Account/AvailableUserList) and see the user list which comes from AvailableUser class.

RenderSection

What is RenderSection?
In layout pages, renders the content of a named section. [MSDN]
How RenderSection Works (graphical presentation)?



RenderSection Example
It’s simple, just add the below code at _layout page.

@RenderSection("Bottom",false)

and add the below code at Index page.

@section Bottom{
This message form bottom.
}

That’s all. But keep in mind that if you don’t want to use the Bottom section in all page then must use the false as second parameter at RenderSection method. If you will mention it as false then it will be mandatory to put Botton section at every content page.
I will be happy, if you found anything wrong or know more please share it via comments.


Continue Reading →

Thursday 21 November 2013

Table Variables In SQL SERVER

Microsoft introduced table variables with SQL Server 2000 as an alternative to using temporary tables. In many cases a table variable can outperform a solution using a temporary table, although we will need to review the strengths and weaknesses of each in this article.

Table variables store a set of records, so naturally the declaration syntax looks very similar to a CREATE TABLE statement, as you can see in the following example

DECLARE @ProductTotals TABLE
(
  ProductID int,
  Revenue money
)

While connected to the Northwind data-base, we could write the following SELECT statement to populate the table variable.


INSERT INTO @ProductTotals (ProductID, Revenue)
  SELECT ProductID, SUM(UnitPrice * Quantity)
FROM [Order Details] GROUP BY ProductID

You can use table variables in batches, stored procedures, and user-defined functions (UDFs). We can UPDATE records in our table variable as well as DELETE records.

UPDATE @ProductTotals
  SET Revenue = Revenue * 1.15
WHERE ProductID = 62

DELETE FROM @ProductTotals
WHERE ProductID = 60

SELECT TOP 5 *
FROM @ProductTotals
ORDER BY Revenue DESC


You might think table variables work just like temporary tables (CREATE TABLE #ProductTotals), but there are some differences.

Scope
Unlike the majority of the other data types in SQL Server, you cannot use a table variable as an input or an output parameter. In fact, a table variable is scoped to the stored procedure, batch, or user-defined function just like any local variable you create with a DECLARE statement. The variable will no longer exist after the procedure exits - there will be no table to clean up with a DROP statement.

Although you cannot use a table variable as an input or output parameter, you can return a table variable from a user-defined function – we will see an example later in this article. However, because you can’t pass a table variable to another stored procedure as input – there still are scenarios where you’ll be required to use a temporary table when using calling stored procedures from inside other stored procedures and sharing table results.

The restricted scope of a table variable gives SQL Server some liberty to perform optimizations.

Performance
Because of the well-defined scope, a table variable will generally use fewer resources than a temporary table. Transactions touching table variables only last for the duration of the update on the table variable, so there is less locking and logging overhead.

Using a temporary table inside of a stored procedure may result in additional re-compilations of the stored procedure. Table variables can often avoid this recompilation hit. For more information on why stored procedures may recompile, look at Microsoft knowledge base article 243586 (INF: Troubleshooting Stored Procedure Recompilation).

Other Features
Constraints are an excellent way to ensure the data in a table meets specific requirements, and you can use constraints with table variables. The following example ensures ProductID values in the table will be unique, and all prices are less then 10.0.

UPDATE @ProductTotals
  SET Revenue = Revenue * 1.15
WHERE ProductID = 62

DELETE FROM @ProductTotals
WHERE ProductID = 60

SELECT TOP 5 *
FROM @ProductTotals
ORDER BY Revenue DESC

You can also declare primary keys. identity columns, and default values.

UPDATE @ProductTotals
  SET Revenue = Revenue * 1.15
WHERE ProductID = 62

DELETE FROM @ProductTotals
WHERE ProductID = 60

SELECT TOP 5 *
FROM @ProductTotals
ORDER BY Revenue DESC

So far it seems that table variables can do anything temporary tables can do within the scope of a stored procedure, batch, or UDF), but there are some drawbacks.

Restrictions
You cannot create a non-clustered index on a table variable, unless the index is a side effect of a PRIMARY KEY or UNIQUE constraint on the table (SQL Server enforces any UNIQUE or PRIMARY KEY constraints using an index).

Also, SQL Server does not maintain statistics on a table variable, and statistics are used heavily by the query optimizer to determine the best method to execute a query. Neither of these restrictions should be a problem, however, as table variables generally exist for a specific purpose and aren’t used for a wide range of ad-hoc queries.

The table definition of a table variable cannot change after the DECLARE statement. Any ALTER TABLE query attempting to alter a table variable will fail with a syntax error. Along the same lines, you cannot use a table variable with SELECT INTO or INSERT EXEC queries. f you are using a table variable in a join, you will need to alias the table in order to execute the query.

UPDATE @ProductTotals
  SET Revenue = Revenue * 1.15
WHERE ProductID = 62

DELETE FROM @ProductTotals
WHERE ProductID = 60

SELECT TOP 5 *
FROM @ProductTotals
ORDER BY Revenue DESC

You can use a table variable with dynamic SQL, but you must declare the table inside the dynamic SQL itself. The following query will fail with the error “Must declare the variable '@MyTable'.”

DECLARE @MyTable TABLE
(
  ProductID int ,
  Name varchar(10)
)

EXEC sp_executesql N'SELECT * FROM @MyTable'

It’s also important to note how table variables do not participate in transaction rollbacks. Although this can be a performance benefit, it can also catch you off guard if you are not aware of the behavior. To demonstrate, the following query batch will return a count of 77 records even though the INSERT took place inside a transaction with ROLLBACK.

DECLARE @MyTable TABLE
(
  ProductID int ,
  Name varchar(10)
)

EXEC sp_executesql N'SELECT * FROM @MyTable'

Choosing Between Temporary Tables and Table Variables

Now you’ve come to a stored procedure that needs temporary resultset storage. Knowing what we have learned so far, how do you decide on using a table variable or a temporary table?

First, we know there are situations that which demand the use of a temporary table. This in-cludes calling nested stored procedures which use the resultset, certain scenarios using dy-namic SQL, and cases where you need transaction rollback support.

Secondly, the size of the resultset will determine which solution to choose. If the table stores a resultset so large you require indexes to improve query performance, you’ll need to stick to a temporary table. In some borderline cases try some performance benchmark testing to see which approach offers the best performance. If the resultset is small, the table variable is always the optimum choice.


An Example: Split

Table variables are a superior alternative to using temporary tables in many situations. The ability to use a table variable as the return value of a UDF is one of the best uses of table vari-ables. In the following sample, we will address a common need: a function to parse a delimited string into pieces. In other words, given the string “1,5,9” – we will want to return a table with a record for each value: 1, 5, and 9.

The following user-defined function will walk through an incoming string and parse out the individual entries. The UDF insert the en-tries into a table variable and returns the table variable as a result. As an example, calling the UDF with the following SELECT statement:

SELECT * FROM fn_Split('foo,bar,widget', ',')

will return the following result set.

position value
1           foo
2           bar
3          widget

We could use the resultset in another stored procedure or batch as a table to select against or filter with. We will see why the split function can be useful in the next OdeToCode article. For now, here is the source code to fn_Split.

if exists (select * from dbo.sysobjects where id = ob-ject_id(N'[dbo].[fn_Split]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_Split]
GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO

CREATE  FUNCTION fn_Split(@text varchar(8000), @delimiter varchar(20) = ' ')
RETURNS @Strings TABLE
(   
  position int IDENTITY PRIMARY KEY,
  value varchar(8000)  
)
AS
BEGIN

DECLARE @index int
SET @index = -1

WHILE (LEN(@text) > 0)

  BEGIN
    SET @index = CHARINDEX(@delimiter , @text) 
    IF (@index = 0) AND (LEN(@text) > 0) 
      BEGIN 
        INSERT INTO @Strings VALUES (@text)
          BREAK 
      END

    IF (@index > 1) 
      BEGIN 
        INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))  
        SET @text = RIGHT(@text, (LEN(@text) - @index)) 
      END
    ELSE
      SET @text = RIGHT(@text, (LEN(@text) - @index))
    END
  RETURN

END
GO

SET QUOTED_IDENTIFIER OFF
GO

SET ANSI_NULLS ON
GO


Summary

Next time you find yourself using a temporary table, think of table variables instead. Table variables can offer performance benefits and flexibility when compared to temporary tables, and you can let the server clean up afterwards.

one more usefull link is Click here


Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives