ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET Hosting - ASPHostPortal.com :: How to Import or Upload and Display Excel File in GridView Using C# in ASP.NET

clock April 13, 2015 06:19 by author Ben

My previous article discussed about How Displaying Validation Errors with ASP.NET MVC. Now in this article, I’ve covered a brief introduction about How to Import or Upload and Display Excel File in GridView Using C# in ASP.NET. There are lots of ways for Importing data from Excel to ASP.NET using C#, and here I’m going to introduce one simple common method to import data.

First we will create a new excel sheet with some data.

So for this article 1st I'll create a new asp.net application and add the beneath code inside your web page.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!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 runat="server">
    <title>Excel File Upload Or Import and Display In GridView Using C# In Asp.Net</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="btnUpload" runat="server" Text="Upload & Display" OnClick="btnUpload_Click" />
    <br />
    <br />
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
    <br />
    </form>
</body>
</html>

Now please check the code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.OleDb;
using System.Data;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string fileExtention = System.IO.Path.GetExtension(FileUpload1.FileName);
                if (fileExtention == ".xls" || fileExtention == ".xlsx")
                {
                    string fileName = System.IO.Path.GetFileName(FileUpload1.FileName);
                    FileUpload1.SaveAs(Server.MapPath("~/ExcelSheet/" + fileName));
                   /*Read excel sheet*/
                    string excelSheetFilename = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("~/ExcelSheet/" + fileName) + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                    OleDbConnection objcon = new OleDbConnection(excelSheetFilename);
                    string queryForExcel = "Select * from [UserDetail$];";
                    OleDbDataAdapter objda = new OleDbDataAdapter(queryForExcel, objcon);
                    DataSet objds = new DataSet();
                    objda.Fill(objds);
                    if (objds.Tables[0].Rows.Count > 0)
                    {
                        GridView1.DataSource = objds.Tables[0];
                        GridView1.DataBind();
                    }
                }
                else
                {
                    lblMessage.Text = "Please upload excel sheet.";
                }
            }
        }
    }
}

Now in above code I've very first read the file and saved inside a folder and also the I study the excel sheet and stored in dataset and bind it towards the gridview manage.

Now we will develop the folder.


Within this folder we'll upload the file as shown in code.

Now we've accomplished run the application and check the output.


Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET MVC Hosting - ASPHostPortal.com :: How Displaying Validation Errors with ASP.NET MVC

clock April 2, 2015 06:21 by author Ben

Today, I write about how Displaying Validation Errors with ASP.NET MVC. We all know how crucial it is to validate user input, but it’s equally crucial how we present validation errors for the user. Take the following type:


The e mail field needs to be optional but any address entered must be valid. If a validation error happens, it ought to replace the optional label using the error message.

Behind the scenes I’m employing Data Annotations to validate the email address, so any errors is going to be passed into the ModelState. MVC has built-in help for displaying these errors (using the ValidateMessageFor helper) so it is easy to create a wrapper around that, supplying the ‘optional’ text as a parameter.

Here’s an extension method for the HtmlHelper:

public static class ExtensionMethods
{
    public static MvcHtmlString HelpMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string helpText)
    {
        var validation = htmlHelper.ValidationMessageFor(expression);
        if (validation == null)
            return new MvcHtmlString("<span class='help-inline muted'>" + helpText + "</span>");
        else
            return validation;
    }
}

Here’s it’s usage:

<fieldset>
  <div class="control-group">
        @Html.LabelFor(x => x.EmailAddress, "Email", new { @class = "control-label" })
        <div class="controls">
            @Html.TextBoxFor(x => x.EmailAddress, new { @class = "input-xlarge", placeholder = "Enter an email address" })
            @Html.HelpMessageFor(x => x.EmailAddress, "Optional")
        </div>
    </div>
</fieldset>

Best ASP.NET MVC Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASPHostPortal.com Announces Reliable Zikula 1.4.0 Hosting Service

clock March 12, 2015 09:11 by author Ben


ASPHostPortal.com, the leader of ASP.NET & Windows hosting provider launches Reliable Zikula 1.4.0 Hosting with comprehensive package.


With the Best excellent service, ASPHostPortal.com is one of the primary Windows hosting providers providing good quality provider with quality assistance. Their servers are built using the most current know-how. They're enthusiastic about web hosting and attempt to deliver an outstanding degree of assistance to each customer. Their world wide web hosting options are well suited for tiny to medium-sized weblogs, personal, charity or business websites. Currently, they launch Zikula 1.4.0 Hosting with reliable technology and cost-effective value.

Zikula is an open source site builder that is quick and simple to use. Using a number of themes, plugins, and user-friendly tools, it is a simple and highly flexible method to get your business webpage, online shop, or blog up and running. Zikula is a powerful PHP-based application development framework which has content material management capabilities built-in. The idea is to expose all the functionality of a common Application Improvement Framework, with all the up-and-running ease of a conventional CMS.

This is achieved by constructing Zikula on top of other development frameworks and implementing a modular approach to feature development.

The day has ultimately come, ASPHostPortal.com Announces Reliable Zikula 1.4.0 Hosting. Zikula 1.4.0 has Symfony at it is foundation, which consists of Doctrine. And Zikula 1.4.0 integrates Twitter's Bootstrap 3 and Font Awesome 4 and utilizes jQuery for exciting web user-interfaces and effects.

"Zikula : an OpenSource PHP Application Framework and CMS for the site, No matter what your demands, Zikula can give the solution. Whether it is a big corporate web presence with ecommerce, a little basic blog or a community portal, Zikula can do it all. Zikula is infinitely expandable with modules and plugins that may add the functionality you need. And all with tomorrow's technology. Greatest of all, it really is totally totally free. ASPHostPortal provides you with the support and help you need," said Dean Thomas, Manager at ASPHostPortal.com.

With 7 data centers that located in USA, Europe, Australia and Asia, ASPHostPortal is superior provider in the hosting market place. They supplies Zikula 1.4.0 Hosting only from $5/month with 30 days funds back assure. Furthermore, ASPHostPortal has been awarded as one from the very best hosting firms within the market due to the excellent hosting overall performance this hosting offers. To supply ideal hosting functionality, this company often maintains the server with expert group in ASP.NET Technology. To learn a lot more about Zikula 1.4.0 Hosting, please visit http://asphostportal.com/Zikula-1-4-0-Hosting

About ASPHostPortal.com

ASPHostPortal.com will be the Reliable, Cheap and Recommended Windows & ASP.NET Hosting. ASPHostPortal.com has capability to support the latest Microsoft and ASP.NET technologies, such as: like: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 5, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch. ASPHostPortal include shared hosting, reseller hosting, and sharepoint hosting, with speciality in ASP.NET, SQL Server, and architecting very scalable options. ASPHostPortal.com strives to provide most likely the most technologically advanced hosting solutions obtainable to all customers the world over. Protection, trustworthiness, and efficiency are on the core of hosting operations to create particular each website and software hosted is so secured and performs at the ideal feasible level.




ASP.NET Hosting - ASPHostPortal.com :: Utilizing Compass Framework with ASP.NET MVC Application

clock March 7, 2015 08:11 by author Ben

In my preceding post I described Greatness ASP.NET Web Config File. In this post I'm taking subsequent step - start off working with Compass - CSS Authoring Framework. Instantly right after installing Internet Workbench, you'll be able to create/edit SCSS file, which are compiled into CSS. By default, Internet Workbench compile SCSS files with SASS compiler. But there's a trick:

Setup Compass Project
Appropriate click on project node in answer explorer, then pick "Setup Compass Project"

It will modify your project by adding "sass" folder with "ie.scss", "print.scss" and "screen.scss" files and compass project configuration file "config.rb" in root.

"config.rb" is really a Ruby file, contains configuration properties, such "css_dir" - the directory where the css stylesheets are kept and "sass_dir" - the directory where the sass stylesheets are kept.

From now, all SASS files, positioned in "sass_dir" will be complied by Compass compiler and, accordingly, CSS output files will be stored in "css_dir".

Should you never desire to alter your ASP.NET project layout, you could choose to adjust Compass configuration.

I choose to help keep all SCSS files in separate directory, consequently I produced "Content/scss" folder and moved existing *.scss files there.
Then I changed config.rb file as bellow:

# Set this to the root of your project when deployed:
http_path = "/"
css_dir = "Content"
sass_dir = "Content/scss"
images_dir = "images"
javascripts_dir = "Scripts"

Now Internet Workbench recognizes scss files as part of Compass project and runs Compass compiler against them. Output css files stay within the identical place, so no need to update views.

Get Magic of Compass

Just open Compass API references and commence coding. Lest consume certainly one of standard functions of Compass - Reset. add following line in beginning of SCSS file @import "compass/reset"; The only line will create plenty of reset rules in output css


Compass has a large amount of valuable functions, and all of them are obtainable in your ASP.NET application.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: How to Debugging ASP.NET vNext Beta Builds with Visual Studio 14

clock March 4, 2015 06:21 by author Ben

Nowadays, I was operating on a sample project with ASP.NET vNext. I've been functioning on this application without any Visual Studio IDE help but I decided to learn what Visual Studio 14 CTP 3 is bring to the table. I realize that Visual Studio CTP three has launched a whilst back and I was expecting to possess problems functioning with ASP.NET vNext beta builds. I was partially right. I wasn’t able to run the web application from Visual Studio. Even so, it is nevertheless feasible to debug the application and I have a workaround for you personally :)

As I was thinking in the quite starting that I would have trouble with VS 14 CTP three + vNext beta builds, I started establishing my environment in the command line instead of letting the VS deal with this.


Nevertheless, Visual Studio nonetheless insisted on installing the Aplha3 builds of the K Runtime but anyways. That is not massive of a deal provided that I have the beta 1 as the active runtime. When I open up the answer, almost everything looked OK. Even the package restore was profitable.

The develop was also functioning. Amazing!

So, it was all going wonderful till I realized that I was building with the OutputType set to "Class Library".

As soon as I changed it to web Application, the develop broke:

This really is OK and anticipated as factors have changed considering that Visual Studio 14 CTP three shipped. However, I’m unable to debug my application now. Hmm, not totally. You'll find still choices and I went using the simpler a single. I switched back to command line and ran the application from there with "k web" command:

All great as it is possible to see. Now, back to Visual Studio and press CTRL + ALT + P to bring up the Attach Process dialog box. We're searching for klr.exe to attach but you will probably see two instances of klr there. We want the one that in fact hosts our application. You can find out which 1 will be the actual host by searching at the command line arguments in the Task Manager.

In my case, it’s using the PID 1472. Finally, attach the approach and also you should have the ability to debug the application now.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.




ASP.NET MVC Hosting - ASPHostPortal.com :: Secure Your ASP.NET MVC Apps and Utilize Active Directory

clock February 25, 2015 06:11 by author Ben

Securing your ASP.NET MVC application ought to be priority number a single each time you begin a brand new net application. Employing the attributes Authorize and ValidateAntiForgeryToken in every single controller and action will be the only method to stay away from any safety holes. In this post I’ll show you the best way to secure your ASP.NET application by implementing the AuthorizeAttribute and ValidateAntiForgeryTokenAttribute classes.

The basics

In the extremely least, you need to add an [Authorize] attribute to every controller or controller Action in case you would like several of the controller actions to be accessible by anonymous users. As an example, you probably want ALL users to possess access for the login and register actions of one's web application.

By decorating the HomeController using the Authorize attribute (notice I didn't specify any user part) the application will avert any unauthenticated user from executing any in the actions in this controller.

[Authorize]
public class HomeController : Controller
{
  //...
}

The following is an instance of decorating a controller action with all the Authorize attribute, you desire to complete this if you only want to restrict access to a few of the actions in a controller instead of all actions.

[Authorize]
public ActionResult Create()
{
  //...
}

Safeguarding against Cross-site request forgery attack (CSRF or XSRF)

The Authorize attribute delivers protection which is sufficient in most situations. Nonetheless, there's security hole with this and therefore it opens your web application for a cross-site request forgery attack. By way of example, right after a user logs into your website the website will concern your browser an authentication token inside a cookie. Every single subsequent request, the browser sends the cookie back for the site to let the web site realize that you are authorized to take what ever action you are taking, so far every thing is very good.

Right here would be the issue with only using the Authorize attribute, let’s say that a user is logged in to your website and then they visit a spam web site by clicking on a hyperlink that points to one more web site which causes a kind post back to your site… this can be negative, your browser will send the authentication cookie to your website generating it seem as when the request came out of your website and initiated by an authenticated user when it genuinely didn’t.

The above situation is known as cross-site request forgery and can be avoided by adding the ValidateAntiForgeryToken attribute offered inside the .NET framework, this attribute is employed to detect regardless of whether a server request has been tampered with.

The initial step would be to add the ValidateAntiForgeryToken attribute to every single Post Action as follows:

[HttpPost, Authorize, ValidateAntiForgeryToken]
public ActionResult Create()
{
  //...
}

The next step is to add the HtmlHelper strategy @Html.AntiForgeryToken() inside the type within your view.

The way the ValidateAntiForgeryToken attribute operates is by checking to view that the cookie and hidden kind field left by the Html.AntiForgeryToken() HtmlHelper essentially exists and match. If they do not exist or match, it throws an HttpAntiForgeryException shown beneath:

“A essential anti-forgery token was not supplied or was invalid”

By adding the ValidateAntiForgeryToken for your controller actions your internet site will likely be prepared to stop CSRF/XSRF attacks.

Implementing Forms Authentication using Active Directory (AD)

Often times you might run across a project where you need to authenticate users of your website using Active Directory credentials, the good news is that you can use the existing “Account” controller to achieve this, only a few modifications are necessary.

When you create a new MVC Web Application project and choose the Internet Application template, the Account controller is added to the project, you can use this controller with AD to authenticate your users. For the Account controller to work with AD we need to remove all Actions but the following:

  • Logon()
  • Logon(LogOnModel model, string returnUrl)
  • LogOff()

Your Account controller should look like the following after you remove the unnecessary Actions such as ChangePassword, Register, etc.

public ActionResult LogOn()
        {
            return View();
        }
       
        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect");
                }
            }

            // if we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

After this, go ahead and clean up the AccountModel as well so the only model class left is the LogOnModel:

public class LogOnModel
        {
            [Required]
            [Display(Name = "User name")]
            public string UserName { get; set; }

            [Required]
            [DataType(DataType.Password)]
            public string Password { get; set; }

            [Display(Name = "Remember me?")]
            public string RememberMe { get; set; }
        }

Lastly, add the following to the project’s web.config file:

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: How to Debug Your ASP.NET Projects Running Beneath IIS

clock February 18, 2015 06:06 by author Ben

If you've carried out any coding in ASP.NET then you understand how critical debugging is. By default Visual Studio comes with its personal stripped down web service that it runs every single time you debug your application as a way to serve up pages. 90% of the time that little net server just isn't powerful or quick enough to maintain up with an enterprise level application. A lot of organizations will have you map your web site to [Internet Information Services][IIS] that is a suitable internet server that comes with Windows. IIS features a lot a lot more possibilities and is much more robust for application hosting (understandably considering that which is its whole goal) whereas the little web service that starts inside the default configuration of visual studio hardly compares.


The downside of possessing your application run by IIS is that it's not immediately apparent how you can debug the application. Pressing F5 nevertheless tries to launch the dinky internet service that comes with Visual Studio. Lots of people speedily determine that they could attach to the procedure thread began by IIS for the application it's operating. It really is generally named one thing like "w3wp.exe". You do this by going to the "debug" menu in Visual Studio and then choosing "Attach to Process". This brings up a bit window having a list of running processes. Obtaining the IIS method for the application and clicking attach will then start Visual Studio's debugger. You are able to then hit the pages hosted by IIS and hit your breakpoints within your code.

Even though this really is fine and functions, it is a giant discomfort to visit Debug > Attach to Process every single single time you must debug your application. You can generate a macro that would do the work for you personally, but why create a macro when Visual Studio will actually do it for you. Let me show you how to setup your project to work with IIS by default when debugging. You will not ever need to navigate your procedure tree once more.

You'll find two forms of internet projects in .NET, Internet sites and Web Applications. There is considerably debate about which 1 is far better for development, but this post is not about that so I will not get into it right here. Nonetheless, these two project varieties have distinct properties menus and configuring them to use IIS when debugging is slightly different in each and every of them. For simplicity's sake I decided to break it up into two sections, one for net apps, and one for websites. Please see the section that corresponds for your project variety. (If you're making use of ASP.NET MVC then you are utilizing a internet application)

Web sites

If your project is actually a website and not a net app, then listed below are the measures to configure it to use IIS when debugging. This assumes you already have IIS setup and hosting your project.

  1. First open up your project and open the solution explorer.
  2. Right-click on your project node and navigate to "Property Pages".
  3. Navigate to "Start Options" item in the left pane.
  4. In the "Server" section make sure "Use custom server" is checked.
  5. In the "Base URL:" field put in the address you have mapped to your project. (Usually the address you put in your hosts file)
  6. You're basically done, but another option I like to set on this page is "Don't open a page. Wait for request from an external application." I set this because I don't like closing a million browser tabs for every time I debug. I usually just leave my browser open behind visual studio and when I debug I prefer to just switch to the browser and refresh rather than have Visual Studio open a new tab.

Web Applications

If your project is a web application and not a website, then here are the steps to configure it to use IIS when debugging.

  1. First open up your project and open the solution explorer.
  2. Right-click on your project node and navigate to "Properties".
  3. Find the "Web" tab on the left-hand side.
  4. Under the "Servers" section select "Use Local IIS Web Server".
  5. This next step varies by how you have your project set up.
    • If you have your project mapped to IIS already then simply put the local URL in the "Project Url" field.
    • If you have NOT mapped your project to IIS yet then it is usually more convenient to click the "Create Virtual Directory" button and let it do it for you. (If you have not set up IIS on your machine correctly then this will fail) Note: Keep in mind that this is not the same as creating a new website in IIS. It creates a virtual directory under the default website that comes with IIS. This can cause problems if you were bad and you used application relative paths instead of absolute paths as root relative paths refer to the website root, not the virtual directory root. Learn how to make your web project build absolute paths based on an application relative root path using the tilde (~).

You're basically done, but another option I like to set on this page is "Don't open a page. Wait for request from an external application." I set this because I don't like closing a million browser tabs for every time I debug. I usually just leave my browser open behind visual studio and when I debug I prefer to just switch to the browser and refresh rather than have Visual Studio open a new tab.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.





ASP.NET Hosting - ASPHostPortal.com :: return View() vs return RedirectToAction() vs return Redirect() vs return RedirectToRoute()

clock January 28, 2015 05:47 by author Ben

There are various approaches for returning/rendering a view in MVC Razor. Numerous developers got confused when to utilize return View(), return RedirectToAction(), return Redirect() and return RedirectToRoute(). In this article, I'd prefer to explain the difference amongst "return View()" and "return RedirectToAction()", "return Redirect()" and "return RedirectToRoute()".


return View()

This tells MVC to create HTML to become displayed for the specified view and sends it to the browser. This acts like as Server.Transfer() in Asp.Net WebForm.


    public ActionResult Index()
    {
    return View();
    }
    
    [HttpPost]
    public ActionResult Index(string Name)
    {
    ViewBag.Message = "Hi, Dot Net Tricks";
    //Like Server.Transfer() in Asp.Net WebForm
    return View("MyIndex");
    }
    
    public ActionResult MyIndex()
    {
    ViewBag.Msg = ViewBag.Message; // Assigned value : "Hi, Dot Net Tricks"
    return View("MyIndex");
    }


What happens if we contact the action strategy directly like return MyIndex(). It is basically a technique call which returns a rendered view which is specified in MyIndex() action method.

public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string Name)
{
ViewBag.Message = "Hi, Dot Net Tricks";
//Like Server.Transfer() in Asp.Net WebForm
return MyIndex();
}
public ActionResult MyIndex()
{
ViewBag.Msg = ViewBag.Message; // Assigned value : "Hi, Dot Net Tricks"
return View("MyIndex");

}

return RedirectToAction()

This tells MVC to redirect to specified action instead of rendering HTML. In this case, browser receives the redirect notification and make a new request for the specified action. This acts like as Response.Redirect() in Asp.Net WebForm.
Moreover, RedirectToAction construct a redirect url to a specific action/controller in your application and use the route table to generate the correct URL. RedirectToAction cause the browser to receive a 302 redirect within your application and gives you an easier way to work with your route table.


    public ActionResult Index()
    {
    return View();
    }
    [HttpPost]
    public ActionResult Index(string Name)
    {
    ViewBag.Message = "Hi, Dot Net Tricks";
    //Like Response.Redirect() in Asp.Net WebForm
    return RedirectToAction("MyIndex");
    }
    public ActionResult MyIndex()
    {
    ViewBag.Msg = ViewBag.Message; // Assigned value : Null
    return View("MyIndex");
    }


return Redirect()

This tells MVC to redirect to specified URL instead of rendering HTML. In this case, browser receives the redirect notification and make a new request for the specified URL. This also acts like as Response.Redirect() in Asp.Net WebForm. In this case, you have to specify the full URL to redirect.
Moreover, Redirect also cause the browser to receive a 302 redirect within your application, but you have to construct the URLs yourself.


    public ActionResult Index()
    {
    return View();
    }
    
    [HttpPost]
    public ActionResult Index(string Name)
    {
    ViewBag.Message = "Hi, Dot Net Tricks";
    //Like Response.Redirect() in Asp.Net WebForm
    return Redirect("Home/MyIndex");
    }
    
    public ActionResult MyIndex()
    {
    ViewBag.Msg = ViewBag.Message; // Assigned value : Null
    return View("MyIndex");
    }


return RedirectToRoute()

This tells MVC to look up the specifies route into the Route table that is is defined in global.asax and then redirect to that controller/action defined in that route. This also make a new request like RedirectToAction().

Defined Route


    public static void RegisterRoutes(RouteCollection routes)
    {
    routes.MapRoute(
    "MyRoute", // Route name
    "Account/", // URL
    new { controller = "Account", action = "Login"} // Parameter defaults
    );
    routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "MyIndex", id = UrlParameter.Optional } // Parameter defaults
    );
    }


HomeController

public ActionResult Index()
{
return View();
}

[HttpPost]
public ActionResult Index(string Name)
{
return RedirectToRoute("MyRoute");
}

AccountController

public ActionResult Login()
{
return View();
}

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers SSRS hosting starts from $5/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable SSRS Hosting, ASPHostPortal.com should be your best choice.



ASP.NET MVC Hosting - ASPHostPortal.com :: Conditional Validation Utilize ValidationAttribute

clock January 21, 2015 05:57 by author Ben

In ASP.NET MVC we can validate each input field by decorating the corresponding property in the model class with some validation attributes like Required, MaxLength, MinLength, etc.

Sometime we need to validate a property according to another property value for example if we have a registration form and we need the user enter his age if he is a male and age not required if the user sex is female. So if we decorated the Age property with Required attribute it will show error message even if the user is female, so we need to bypass this check with females.

Assume our registration form will contains three fields, name, sex and age, and its model will be as follows

public class RegisterationModel
{
    [Required(ErrorMessage = "*")]
    public String Name { get; set; }

    [Required(ErrorMessage = "*")]
    [Display(Name = "Gender")]
    public Sex Sex { get; set; }

    [RequiredIf("Sex", Sex.Male, "enter your age")]
    public Int32? Age { get; set; }
}
public enum Sex
{
    Female = 1,
    Male = 2
}

Note we decorated the Age property with RequiredIf attribute, that we will create and it inherits ValidationAttribute class and override IsValid method.

The RequiredIf attribute accepts three pramaters in its constructor, first parameter is the name of the property will affect the validation (Sex property), second parameter is the value of that property that make the Age is required(Male), and third parameter is the error message that will be displayed if the validation failed.

public class RequiredIfAttribute : ValidationAttribute
{
    private String PropertyName { get; set; }
    private String ErrorMessage { get; set; }
    private Object DesiredValue { get; set; }

    public RequiredIfAttribute(String propertyName, Object desiredvalue, String errormessage)
    {
        this.PropertyName = propertyName;
        this.DesiredValue = desiredvalue;
        this.ErrorMessage = errormessage;
    }

    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        Object instance = context.ObjectInstance;
        Type type = instance.GetType();
        Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
        if (proprtyvalue.ToString() == DesiredValue.ToString() && value == null)
        {
            return new ValidationResult(ErrorMessage);
        }
        return ValidationResult.Success;
    }
}

In the IsValid method we get the current instance of RegisterationModel class using ValidationContext object and get the value of the Sex property then compare it with the desire value(Male) which make the Age is required. If the current value of Sex property equal the desired value then IsValid will return new ValidationResult object with the supplied error message.

Unfortunately this technique is working in server side only.


Recommended ASP.NET MVC 6 Hosting


ASPHostPortal.com
ASPHostPortal.com
is the leading provider of Windows hosting and affordable ASP.NET MVC Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.




ASP.NET MVC Hosting - ASPHostPortal.com :: Donut Caching with ASP.NET MVC 6

clock January 14, 2015 06:03 by author Ben

I'm working on a new personal project during my free time and I chose to develop it with ASP.NET MVC 6 (hosted on ASPHostPortal of course...) to test the new features of this version. In this project, I need to display "Logged in as xxxx " (if the user is logged...) in the header of the page. This is a simple scenario to implement but caching could complicate the development of my web app...



My header is in my layout and is used everywhere but I would like to place an OutputCacheAttribute on some actions (the home page, etc.). If I put the attribute on an action, all of my users will see an header with "logged in as xxxx" of the first incoming query!

The solution to this problem is named "Donut Caching": you send a cached page from the server with a "fresh" portion which is not in cache (the donut's hole).
Concretely, the server does not generate the requested page (query the DB, etc.): it just needs to take the cached version and replace a specific part.

Luckily, you do not need to develop your own custom OutputCacheAttribute because there is already a very good package (There's An App A Pack For That... thanks NuGet!): MvcDonutCaching for ASP.NET MVC 3 and later...

To install the package, you can search through NuGet or directly type the following command in the "Package Manager Console":

install-package MvcDonutCaching

The use of this package is very simple... They have created several extension methods for HtmlHelper with the usual parameters plus another boolean parameter: excludeFromParentCache. I just have to call my partial view (with the "connected has xxxx"...) like that:

@Html.Action("LoginHeader", "Account", new { lang }, true)\

The last parameter of Html.Action is set to true: this partial view will be excluded from the parent cache (if there is a cache on the action...). (do not pay attention to new { lang }, it's a route's value) To make it work, you must not use the OutputCacheAttribute but the DonutOutputCacheAttribute:

[DonutOutputCache(Duration = 60, VaryByParam = "lang")]
     public ActionResult Index(string lang)
     {
         ...
     
         return View();
     }

And that's it! The first request will be cached during 60 seconds but the LoginHeader partial view will be generated every time.

(note: of course, the donut caching only works on the server side...)

Best Hosting for Your ASP.NET MVC Hosting

Following reviewed for Best ASP.NET hosting companies that help with ASP.NET MVC, ASPHostPortal is Best ASP.NET Hosting Recommendation for ASP.NET MVC. They give 99,99% uptime assured, as well as 30 Days Money back assured, superb customer service, and many more.



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in