ASP.NET 4.5 Hosting BLOG

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

ASP.NET Hosting - ASPHostPortal.com :: RowDatabound event tips and tricks in Gridview control

clock January 30, 2015 06:39 by author Dan

In this article, I will depict about few tips and tricks in rowdatabound occasion which is accessible in ASP.NET gridview control and these tips will give the answer for all conceivable necessities when working with rowdatabound occasion in gridview control.

Introduction

Gridview control is most regular control in all asp.net applications to show the information and its capable control and parcel of implicit peculiarities. In this article, i will investigate a few tips and traps in rowdatabound occasion in gridvew control, Actually Rowdatabound occasion will happen when information column is sure to the control in the gridview control.

Discover control in Rowdatabound occasion

Utilizing this occasion we can ready to discover the particular controls, for example, textbox, dropdown, checkbox and get values from control which is utilized inside gridview control.

protected void GVSample_RowDataBound(object sender, GridViewRowEventArgs e)
        {   //Get data row view
            DataRowView drview = e.Row.DataItem as DataRowView;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //Find dropdown control & get values
                DropDownList dpEmpdept = (DropDownList)e.Row.FindControl("DrpDwnEmpDept");
                string value = dpEmpdept.SelectedItem.Value;
                //Find textbox control
                TextBox txtname = (TextBox)e.Row.FindControl("txtName");
                string Name = txtname.Text;
                //Find checkbox and checked/Unchecked based on values
                CheckBox chkb = (CheckBox)e.Row.FindControl("ChckBxActive");
                if (drview[5].ToString() == "True")
                {
                    chkb.Checked = true;
                }
                else
                {
                    chkb.Checked = false;
                }
            }
        }

Format specific row

We can ready to do arranging a particular column in a gridview focused around a few conditions, say for instance if value would be all the more then 100 then show, those columns with foundation as tan, fore shade as dark and striking letters.

protected void GVSample_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label lblPrice = (Label)e.Row.FindControl("lblPrice");
                if (Convert.ToInt32(lblPrice.Text) > 100)
                {
                    e.Row.ForeColor = System.Drawing.Color.Black;
                    e.Row.Font.Bold = true;
                    e.Row.BackColor = System.Drawing.Color.Brown; 
                }
            }
        }

Gridview row color change

In the event that you need to change the gridview column shade change on mouse over and mouse out then compose the beneath code in rowdatabound occasion.

protected void GVSample_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "self.MouseOverOldColor=this.style.backgroundColor;this.style.backgroundColor='#C0C0C0'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=self.MouseOverOldColor");
            }
        }

Bind dropdown list in footer

At some point we utilize footer column to include/supplement records, so for this situation in the event that you utilize dropdown list as a part of footer line to include new record then we have to load the information in dropdown list when scrape the information with gridview control and see the beneath code in what manner would we be able to load dropdown list in footer column while rowdatabound occasion happens.

protected void GVSample_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                DropDownList dp = (DropDownList)e.Row.FindControl("DrpDwnAddEmpDept");
                dp.DataSource = GetEmpDept();
                dp.DataTextField = "DepName";
                dp.DataValueField = "DepName";
                dp.DataBind();
            }
        }
        private DataTable GetEmpDept()
        {
            //Get Employee department
            DataTable dt = new DataTable();
            dt.Columns.Add("DepName");
            DataRow rw1 = dt.NewRow();
            rw1[0] = "IT";
            dt.Rows.Add(rw1);
            DataRow rw2 = dt.NewRow();
            rw2[0] = "Finance";
            dt.Rows.Add(rw2);
            DataRow rw3 = dt.NewRow();
            rw3[0] = "Security";
            dt.Rows.Add(rw3);
            return dt;
        }

HyperLink and redirect

By and large we utilize hyperlink to divert other page or open new page to view particular subtle elements focused around a few conditions, beneath case diverting to other page if client is qualified to view.

<asp:GridView ID="GVSample" runat="server" AutoGenerateColumns="false" OnRowDataBound="GVSample_RowDataBound">
            <Columns>
                <asp:TemplateField HeaderText="Userprofile">
                    <ItemTemplate>
                        <asp:HyperLink ID="hyprlnkdetails" runat="server" />
                        <asp:Label ID="lblText" runat="server" Text=""></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

protected void GVSample_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            DataRowView drview = e.Row.DataItem as DataRowView;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                HyperLink HLdetails = e.Row.FindControl("hyprlnkdetails") as HyperLink;
                Label lblText       = e.Row.FindControl("lblText") as Label;
                if (drview[5].ToString()=="True")
                {
                    HLdetails.Text          = "Click here to view";
                    HLdetails.NavigateUrl   = String.Format("~/details.aspx?UserID={0}", drview[8].ToString());
                }
                else
                {
                    HLdetails.Visible   = false;
                    lblText.Text        = "View Restricted";
                }
            }
        }

Get DataKeyValues in RowDatabound

For the most part we set the essential key qualities to the datakeyname property in gridview control and underneath code will help to get that date key qualities connected with a line in rowdatabound occasion.

protected void GVSample_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                    string userID = GVSample.DataKeys[e.Row.RowIndex].Values[0].ToString();
            }
        }

Above rundown of tips on rowdatabound occasion in gridview control will help you when work with this occasion, a debt of gratitude is in order regarding perusing this article and give your proposals and criticism about this article.

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 to Use Areas in ASP.NET MVC

clock January 29, 2015 05:57 by author Mark

Today i will explains about how to use areas in ASP.NET MVC. When we create a new MVC project then Model, View and Controller folders are created automatically.
This structure is common for simple applications, but when your application grows and becomes complex then the single Model, View and Controller can become complicated. So we can maintain a complex MVC application using areas. Using areas, we can write more maintainable code for an application cleanly separated by the modules.

Step by Step

  • So first create a new MVC empty project.
  • Then right-click on Solution Explorer and click on add and select area.

  • Provide a name.

  • Now add a second Employee area. In your Solution Explorer show your Model, View and Controller in a different student and employee area.

  • Now add a Home Controller and in the Index action add an Index View for both the student and employee area.
  • Now run the project. (Ctrl+F5).
  • For the Teacher area the follwing is the URL localhost/Teachers/Home/Index.
  • Here Teachers is the area name, Home is the controller and Index is the Action name.

  • For the Teacher area the follwing is the URL localhost/Students/Home/Index.
  • Here Students is the area name, Home is the controller and Index is the Action name.

TOP No#1 Recommended ASP.NET MVC 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 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.



ASPHostPortal.com Proudly Announces Classic ASP Hosting with Persits

clock January 27, 2015 10:56 by author Dan

Providing low cost web hosting, ASPHostPortal.com has become one of The Best, Cheap and Recommended ASP.NET Hosting. We offer Classic ASP with Persits Hosting with a combination of affordable price, excellent network, and 30 days money back guarantees. We also provide full trust web hosting services for Classic ASP with Persits site.

Since 1997, Persits Software engineers have been building server-side components for the Microsoft Windows environment that are now used by tens of thousands of companies, universities and government agencies all over the World. Their dedication to quality has won them a worldwide reputation as the leader in the server component market.

The Active Server components they offer help Web developers harness browser-based file uploading, image resizing, PDF generation, Windows security, data encryption, secure messaging, database publishing, and SMTP email in just a few lines of code. Developed by the most powerful development tools on the market, their components are reliable, fast, and easy to use.

ASPHostPortal.com, a windows-based hosting service provider offers the most reliable and stable Classic ASP with Persits web hosting infrastructure on the net with great features, fast and secure servers. We have built the network like no other hosting company. Every facet of the network infrastructure scales to gigabit speeds with no single point of failure. All of windows hosting plan supports Classic ASP with Persits and customers can install it with just one click. We offer professional Classic ASP with Persits site start from $5/month. The following are the reasons why the customers choose and keep trust with our service:

High Performance and Reliable Server
We never ever overload the server with tons of clients. We always load balance the server to make sure we can deliver an excellent service, coupling with the high performance and reliable server.

Daily Backup Service
We realize that customer’s website is very important to their business and hence, we never ever forget to create a daily backup.

Best and Friendly Support
Our support team is extremely fast and can help you with setting up and using Classic ASP with Persits on your account. Ourcustomer support will help you 24 hours a day, 7 days a week and 365 days a year.

With the Classic ASP with Persits in our hosting deal will make us continue to be the Best ASP.NET hosting providers. To learn more about Classic ASP with Persits Hosting, please visit http://asphostportal.com/Persits-ASPGrid-Hosting

About ASPHostPortal.com :
ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET Hosting. ASPHostPortal.com has ability to support the latest Microsoft and ASP.NET technology, such as: 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 include shared hosting, reseller hosting, and sharepoint hosting, with speciality in ASP.NET, SQL Server, and architecting highly scalable solutions. ASPHostPortal.com strives to supply probably the most technologically advanced hosting solutions available to all consumers the world over. Protection, trustworthiness, and performance are on the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.



ASP.NET Hosting - ASPHostPortal :: Describe the Lifecycle of an ASP. NET Web API Message

clock January 27, 2015 05:36 by author Mark

In this article we will describe the Lifecycle of an ASP. NET Web API message. We know that the ASP. NET Web API is a framework that helps build the services over the HTTP server. It provides the lightweight services used by multiple clients and devices of the platform to access the data via the API. For transferring the data over the wire , it uses the JavaScript Object Notation (JSON) and Extensible Markup Language (XML)
Now we will define the Lifecycle of an ASP. NET Web API Message from the client to the server and the server to the client. The request is generated by the client using HttpRequest and the return response is generated by HttpResponse.

Diagram of Web API Pipeline

Hosting of web API

We perform two types of hosting on the Web API. They are ASP.NET and Selfhosting, as described in the following:

  • ASP.Net Hosting:  When we perform the ASP.NET hosting then the Lifecycle starts from HttpControllerHeader which is the implementation of IHttpAsyncHandler and the responsibility of it is to send the request to the HttpServer pipeline.
  • Self Hosting:  In self hosting the HttpServer pipeline starts from the HttpSelfHostServer that performs the implementation of HttpServer and the responsibility is that it can be directly listen to the HTTP request.

HTTP Message Handler

After leaving the service host the request travels in the pipeline as a HttpRequestMessage. There is the Handler used in the Lifecycle.

Delegating Handler

This handler is provided to you as a Message of the request before passing onto the rest of the pipeline. The response message can be sent through the delegating handler. And other messages can be monitored and filtered at this point.

Routing Dispatcher

When the request is made using the option Delegation Handler it can be passed to the Routing Dispatcher. The dispatcher checks whether the Route Handler is Null. If the the Route Handler is null then it is passed to the next step in the pipeline.
If it is not null then there are many handlers for routing the message and the desired request is passed to the handler. We select the matching message handler to handle the request.

Controllers

After leaving the service host the request is travels in the pipeline as a HttpRequestMessage. These are the handlers used in the Lifecycle.

Authorization Filter

In the control section the first step is passed to the authorization. If there are Authorization Filters available and the authorization is failed by the request then the request is truncated and sent as a auth failure response.

Model Binding

If the authorization test is successful then it is passed to the model binding section. It is not a single-step process.
If we want to see the model binding process then it looks like the following.

View of Model Binding

In the model binding we can see the three parts of the HTTP request; they are URI, Headers and Entity Body.

 

URI

The URI works as a ModelBinderParameterBinder object that checks that there are custom IModelBinder an IValueProvider.

Formatter Binding

The Entity body of the model binding is managed by the FrmatterParameterBinding. If there is a request that needs to utilize one or two Media Type Formatters then it is piped through the appropriate Media Type Formatter.

HTTP parameter binding

There is a need for the entire request to be piped through the HTTP parameter binding module, if there is a custom HTTP Parameter Binding module.

Action Filter

After completion of the Model Binding the Action Filter is done. It is invoked two times in the pipeline before the OnExecuting event and after the OnExecution event.

Action Invoker

The action invoker invokes the actions of the control. It binds and models the state for invoking the action in HttpActionContext. It can invoke the action and also return the message in the form of a HttpResponseMessage. If there is an Exception at the time of invoking the action then the exception is routed to the Exception Filter that can send the Error Message.

Controller Action

Controller Action executes the Action Method code. And it generates the HttpResponseMessage.

Result Conversion

Now we see the image of the Result Conversion:

  • HttpResponseMessage: The message is directly passed in it and nothing needs conversion.
  • Void: The action method returns the void result in it and there is a need for conversion into a HttpPesponseMessage.

If the Action Method returns any other type then the Content Negotiation and Media Type Formatters are used. The Content Negotiation checks that we can return the requested content using the appropriate Media Type formatter.

TOP No#1 Recommended ASP.NET 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 Hosting - ASPHostPortal.com :: Simple trick to use stored Procedure with output parameters with ASP.NET

clock January 26, 2015 07:25 by author Dan

Today, I will explain to you How to use stored Procedure with output parameters with ASP.NET. I have given a basic code case, I have made a store technique with yield parameter. After that I get it from code behind page of asp.net and put away it a variable.

private void GetInfo() 
   { 
     DALUtility objDALUtility = null; 
     SqlConnection con = null; 
     SqlCommand cmd = null; 
     SqlDataAdapter da = null; 
     try 
     { 
       objDALUtility = new DBUtility(ConfigurationManager.AppSettings["myconString"]); 
       con = objDALUtility.GetDBConnection(); 
       con.Open(); 
       cmd = new SqlCommand(); 
       cmd.Connection = con; 
       cmd.CommandType = CommandType.StoredProcedure; 
       cmd.CommandTimeout = 500; 
       cmd.CommandText = "usp_MyInfo"; 
       cmd.Parameters.AddWithValue("@Id", strId); 
       cmd.Parameters.AddWithValue("@empName", Convert.ToString(Session["Name"]));       
       cmd.Parameters.Add("@TotalCount", SqlDbType.Int).Direction = ParameterDirection.Output; 
       da = new SqlDataAdapter(cmd); 
       DataSet objDS = new DataSet("MyInfo"); 
       da.Fill(objDS); 
       con.Close(); 
       int Total = Convert.ToInt32(cmd.Parameters["@TotalCount"].Value); 
     } 
   } 
 Stored Procedure 
 CREATE Proc [dbo].[usp_MyInfo] 
  @Id int,           
  @Name varchar(50) = null,     
  @Total int = 0 OUTPUT 
 AS         
 SET @Total = (Select COUNT(Distinct tbl_Logs.ContentId) From tbl_Logs with(nolock)        
  Inner Join tbl_Logs_details with(nolock) on tbl_Logs_details.ContentId = tbl_Logs.ContentId 
  Where id = @id and tbl_Logs_details.ContentId = 2  
 Select @Total as Count

Finish, just paste that code, your ASP.NET problems solved. Hopefully, it will solve your ASP.NET problems. Any questions, comment here!

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 Hosting - ASPHostPortal :: How to Disable Cut, Copy and Paste in the Entire ASP.NET Web Form

clock January 22, 2015 06:22 by author Mark

This article shows how to restrict the use of cut, copy and paste by the end user in the whole page.

In the real world, sometimes a developer needs to restrict a basic facility such as cut, copy and paste on an entire web page but not on a specific control. At that time you will need some easy way to stop these kinds of facilities on the page but not create code in every control to disable these facilities.
Suppose you have 20 "TextBox" controls in your page and you want to restrict the cut, copy and paste in all the textboxes, then you do not need to write the disable code in each TextBox. In this scenario, you need to just write the disable code only in the "body" tag.
To explain such implementation, I will use the following procedure.

Step 1

Create an ASP.Net Empty Website named "My Project".

Step 2

Add a new web form named "Default.aspx" into it.

Step 3

Add 2 "TextBox" controls to the page named "Default.aspx" .

Step 4

On Cut: By this, you can disable the "Cut " facility in both of the "TextBox" Controls.
Syntax: oncut= “return false”;


On Copy: By this, you can disable the "Copy " facility in both of the "TextBox" controls.
Syntax: oncopy= “return false”;


On Paste: By this, you can disable the "Cut" facility in both of the "TextBox" controls.
Syntax: onpaste= “return false”;

To disable the All (Cut, Copy and Paste) in the entire page:

Conclusion

In this article, I have described how to restrict the user to use the cut, copy and paste facilities in the entire page and I hope it will be beneficial for you.

TOP No#1 Recommended ASP.NET MVC 5 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 :: 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.




ASPHostPortal Announces a New 50% off Promo Code

clock January 20, 2015 10:13 by author Dan

A new 30% off ASPHostPortal promo code is being offered for ASPHostPortal web hosting company services. With the fastest 1,000 Mbps connection backbone, ASPHostPortal has moved and expanded their services. Now They have 7 Data Centers which locate in USN, Netherlands, Singapore, Hong Kong, United Kingdom, Australia, and France.

The Windows web hosting plans consist of Host Intro, Host One, Host Two, and Three. Host One, two, and three plan offers unlimited sites. Each of the plans offers many different features which include Plesk Panel, Dedicated Application Pool, 30 Days Money Back Guarantee, Server & Database Back Up, and Windows 2008/Windows 2012. You can also get support full trust, single click website builder and much, much more. The Host intro plan is available for only $1 per month.

The Host Intro Plan is designed for you who have low budget and want to get best hosting service. This subtle advantage can be quite profound for online businesses, blogging, and portofolio web. In addition, there are a Cloud Hosting that available for only $2 more per month, SharePoint Hosting for $9.99 per month, and Reseller Hosting for $24 per month. Also, there are specially designed plans with add $1 or more per month, but are customized for the customer.

For those who are interested in taking advantage of ASPHostPortal coupon codes or want to know more about what ASPHostPortal web hosting is offering in terms of services, visit http://asphostportal.com/Windows-Hosting-Intro.

About ASPHostPortal.com :

ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET Hosting. ASPHostPortal.com has ability to support the latest Microsoft and ASP.NET technology, such as: 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 include shared hosting, reseller hosting, and sharepoint hosting, with speciality in ASP.NET, SQL Server, and architecting highly scalable solutions. ASPHostPortal.com strives to supply probably the most technologically advanced hosting solutions available to all consumers the world over. Protection, trustworthiness, and performance are on the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.



ASP.NET MVC Hosting - ASPHostPortal :: Describes Attribute Based Routing in ASP.NET MVC 5

clock January 20, 2015 05:19 by author Mark

This article will explains about describes Attribute Based Routing in ASP.NET MVC 5. Today we will have a look at one of the new features introduced in ASP.NET MVC 5, attribute based routing.

Pre-Context

We all know that ASP.NET MVC is a great platform that allows us to create and manage web applications in a much simpler manner compared to form-based web applications. There are a few things in MVC based web applications that works a little differently than standard web applications, one of them is routing.
Until now, there has been a routing table that you can define either in the Global.asax or in the RouteConfig.cs and all incoming requests would look it up to decide the rendering of a target view.
Here is the code that you might have seen previously to have note-variable routes in MVC 4 in the following example of the Route collection object.  

                         routes.MapRoute(  
                name: "Default",  
                url: "{controller}/{action}/{id}",  
                defaults: new { controller = "Product", action = "List", id = UrlParameter.Optional }  
                ); 

The big question: what is the need for this new routing methodology?
And the answer is: there was nothing really wrong with the previous approach of routing and in fact you can still use it in MVC 5 or use this new routing method in conjunction with the old one.
Here are a few advantages of attribute based routing:  

  • Helps developer in the debugging / troubleshooting mode by providing information about routes.
  • Reduces the chances for errors, if a route is modified incorrectly in RouteConfig.cs then it may affect the entire application's routing.
  • May decouple controller and action names from route entirely.
  • Easy to map two routes pointing to the same action.

All right, enough of talking. Let's see exactly how we can configure it and see it working.
First, we will need to enable attribute based routing on our MVC web application that can be done by only one line. All you need to do is put this line in the RegisterRoutes Method of the application.

    public static void RegisterRoutes(RouteCollection routes)  
    {  
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");         
        tes.MapMvcAttributeRoutes(); //Enables Attribute Based Routing   
        routes.MapRoute(  
            name: "Default",  
            url: "{controller}/{action}/{id}",  
            defaults: new { controller = "Product", action = "List", id = UrlParameter.Optional }  
        );                    
    } 

Now, here is how you can use the attribute based routing on a specific action method.

[Route("products/{id?}")]  
          public ActionResult Details(string id)   
          {  
              if (string.IsNullOrEmpty(id))   
              {  
                  return View("List", GetProductList());  
              }                   
              return View("Details", GetProductDetails());  
          }  

As shown in the method above, the Route is defined on a Details action method that lets users access the product details page either by of these paths:  
    /Product/Details/Id or /products/id
You might have observed the question mark in the route above, all it indicates is that the id is an optional parameter of the route and hence the action method logic checks if the id is null. It will show you the product listing page.

Route Prefixes

Route Prefixes are nothing but the prefix for any route that we want to apply, all we need to do is to define the route prefix on a controller so that all the action methods inside it can follow the prefix.
For example:   

         [RoutePrefix("products")]  
          public class ProductController : Controller  
          {  
              //This will be translated to /products          
             [Route]  
              public ActionResult List()  
              {  
                  return View();  
              }          
              //This will be translated to /products/2          
              [Route("{id?}")]  
              public ActionResult Details(string id)   
              {  
                  if (string.IsNullOrEmpty(id))   
                  {  
                     return View("List");  
                  }                       
                  return View("Details");  
              }  
      }

Route Constraints

Route constraints are nothing but a set of rules that you can define on your routing model / parameters that users need to follow when accessing the defined routes.
The way to define a constraint is by using the ":" character, let's have a look at the example below.
For example:

   //route gets called as /products/productname  
        [Route("products/{id:alpha}")]  
            public ActionResult GetProduct(string name)  
            {  
                return View();  
            }         
    //route gets called as /products/2  
            [Route("products/{id:int}")]  
            public ActionResult GetProduct(int id)  
            {  
                return View();  
            } 

Now you might have observed in the example above that though the method name is the same the route's parameter has some constraint on it. In other words the first method will be called if the route is accessed with a string as parameter and the second method will be called if the route is accessed with an integer in the route parameter.
You can also define your custom route constraints using an IRouteConstraint interface.

Route Areas

A Route area is nothing but the way to specify the area in a route, basically just to let the route know that the controller belongs to some area.

[RouteArea("business")]  
      [RoutePrefix("products")]  
      public class ProductController : Controller  
      {  
          //This will be translated to /business/products/list      
          [Route]  
          public ActionResult List()  
          {  
              return View();  
          }  
  }

TOP No#1 Recommended ASP.NET MVC 5 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.

 

 



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