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 4.5 Hosting - ASPHostPortal.com :: Enabling Unobtrusive Validation From Scratch in ASP.NET 4.5 Webforms

clock December 19, 2014 04:55 by author Ben

I used to be fiddling with ASP.NET 4.5 and Visual Studio 2012 particularly with all the new Validation attributes and i identified they function great, specially the new unobtrusive validation, then I attempted to permit this sort of validation over a new Vacant Net Software, and that i identified that this just isn't out-of-the-box, you'll need to create some configurations to your Net Application.

You'll find a few ways to allow the unobtrusive validation over a Internet Software:

Through the web.config file

<configuration> 
  <appsettings> 
   <add key="ValidationSettings:UnobtrusiveValidationMode" value="WebForms"> 
  </add></appsettings> 
 </configuration> 

Via the Global.asax file

protected void Application_Start(object sender, EventArgs e)
{
   ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
}

On each page:

protected void Page_Load(object sender, EventArgs e)
{
   this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.WebForms;
}

To disable the unobtrusive validation set the UnobtrusiveValidationMode property to None. Unobtrusive validation is actually enabled by default in ASP.Net 4.5.

We'll start with a simple example, create an Empty Web Application and add a MasterPage called Site.master and a content page for this master called Default.aspx.
Add the following code to the Default.aspx file:

<asp:TextBox runat="server" ID="txt" />
    <asp:RequiredFieldValidator ErrorMessage="txt is required" ControlToValidate="txt" runat="server" Text="*" Display="Dynamic" />
    <asp:Button Text="Send info" runat="server" />

If you try to run a simple ASPX page using a validator, the following exception will be thrown:

    "WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)". Before fixing this, let's disable the unobtrusive validation to see the result.

On the page:

protected void Page_Load(object sender, EventArgs e)
{
   this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
}

Now run the page and the validation will work as it used to work in ASP.Net 4.0 If you examine the rendered HTML, you will see that the gross inline script is rendered:

<script type="text/javascript">
//<![CDATA[
var Page_Validators =  new Array(document.getElementById("ContentPlaceHolder1_ctl00"));
//]]>
</script>

<script type="text/javascript">
//<![CDATA[
var ContentPlaceHolder1_ctl00 = document.all ? document.all["ContentPlaceHolder1_ctl00"] : document.getElementById("ContentPlaceHolder1_ctl00");
ContentPlaceHolder1_ctl00.controltovalidate = "ContentPlaceHolder1_txt";
ContentPlaceHolder1_ctl00.errormessage = "txt is required";
ContentPlaceHolder1_ctl00.display = "Dynamic";
ContentPlaceHolder1_ctl00.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";
ContentPlaceHolder1_ctl00.initialvalue = "";
//]]>
</script>


<script type="text/javascript">
//<![CDATA[

var Page_ValidationActive = false;
if (typeof(ValidatorOnLoad) == "function") {
    ValidatorOnLoad();
}

function ValidatorOnSubmit() {
    if (Page_ValidationActive) {
        return ValidatorCommonOnSubmit();
    }
    else {
        return true;
    }
}
       
document.getElementById('ContentPlaceHolder1_ctl00').dispose = function() {
    Array.remove(Page_Validators, document.getElementById('ContentPlaceHolder1_ctl00'));
}
//]]>
</script>

Now let's re-enable the unobtrusive validation. In order to fix the previous exception, we need to install the following Nuget packages: (I like to install jQuery first to get the latest version, although this is not required.)

  1. jQuery
  2. ASPNET.ScriptManager.jQuery
  3. Microsoft.AspNet.ScriptManager.MSAjax
  4. Microsoft.AspNet.ScriptManager.WebForms

At this point, if you run the application again, the exception will be gone =) how cool eh?. This is because the following Nuget packages automatically register the scripts needed with the ScriptManager control.

Let's examine the code added by these Nuget packages using ILSpy:

AspNet.ScriptManager.jQuery

public static class PreApplicationStartCode
    {
        public static void Start()
        {
            string str = "1.8.1";
            ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition
            {
                Path = "~/Scripts/jquery-" + str + ".min.js",
                DebugPath = "~/Scripts/jquery-" + str + ".js",
                CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + str + ".min.js",
                CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + str + ".js",
                CdnSupportsSecureConnection = true,
                LoadSuccessExpression = "window.jQuery"
            });
        }
    }

Microsoft.AspNet.ScriptManager.MSAjax

public static void Start()
{
    ScriptManager.ScriptResourceMapping.AddDefinition("MsAjaxBundle", new ScriptResourceDefinition
    {
        Path = "~/bundles/MsAjaxJs",
        CdnPath = "http://ajax.aspnetcdn.com/ajax/4.5/6/MsAjaxBundle.js",
        LoadSuccessExpression = "window.Sys",
        CdnSupportsSecureConnection = true
    });
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjax.js", "window.Sys && Sys._Application && Sys.Observer");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxCore.js", "window.Type && Sys.Observer");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxGlobalization.js", "window.Sys && Sys.CultureInfo");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxSerialization.js", "window.Sys && Sys.Serialization");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxComponentModel.js", "window.Sys && Sys.CommandEventArgs");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxNetwork.js", "window.Sys && Sys.Net && Sys.Net.WebRequestExecutor");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxHistory.js", "window.Sys && Sys.HistoryEventArgs");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxWebServices.js", "window.Sys && Sys.Net && Sys.Net.WebServiceProxy");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxTimer.js", "window.Sys && Sys.UI && Sys.UI._Timer");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxWebForms.js", "window.Sys && Sys.WebForms");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxApplicationServices.js", "window.Sys && Sys.Services");
}
private static void AddMsAjaxMapping(string name, string loadSuccessExpression)
{
    ScriptManager.ScriptResourceMapping.AddDefinition(name, new ScriptResourceDefinition
    {
        Path = "~/Scripts/WebForms/MsAjax/" + name,
        CdnPath = "http://ajax.aspnetcdn.com/ajax/4.5/6/" + name,
        LoadSuccessExpression = loadSuccessExpression,
        CdnSupportsSecureConnection = true
    });
}

Microsoft.AspNet.ScriptManager.WebForms

public static void Start()
{
    ScriptManager.ScriptResourceMapping.AddDefinition("WebFormsBundle", new ScriptResourceDefinition
    {
        Path = "~/bundles/WebFormsJs",
        CdnPath = "http://ajax.aspnetcdn.com/ajax/4.5/6/WebFormsBundle.js",
        LoadSuccessExpression = "window.WebForm_PostBackOptions",
        CdnSupportsSecureConnection = true
    });
}

As you can see these Nuget packages automatically register the scripts using the ScriptManager object (besides installing the required JavaScript files)

Run the application and examine the rendered HTML. You will note that it's much cleaner now, in this case the inline script has been moved to an external file that can be rendered using bundles to increase performance. The rendered script looks like:

<script src="Scripts/WebForms/MsAjax/MicrosoftAjaxWebForms.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.8.1.js" type="text/javascript"></script>

Much better right?. Notice how ASP.Net used HTML5 custom attributes:

<input name="ctl00$ContentPlaceHolder1$txt" type="text" id="ContentPlaceHolder1_txt" />
    <span data-val-controltovalidate="ContentPlaceHolder1_txt" data-val-errormessage="txt is required" data-val-display="Dynamic" id="ContentPlaceHolder1_ctl00" data-val="true" data-val-evaluationfunction="RequiredFieldValidatorEvaluateIsValid" data-val-initialvalue="" style="display:none;">*</span>
    <input type="submit" name="ctl00$ContentPlaceHolder1$ctl01" value="Send info" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$ContentPlaceHolder1$ctl01&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" />

The data-val-* are custom attributes used by the unobtrusive validation engine

If you click the button to trigger the validation you will be pleased to see that it works as expected...but we are not done yet =/

The settings we have applied won't work if you intend to use an UpdatePanel control (yeah the evil UpdatePanel again...). This is because this control requires a ScriptManager control on the page (or MasterPage) and we do not have any yet. So let's add a simple ScriptManager control to the master page and see what happens. Add the following code to the Site.master page right under the <form...

<asp:ScriptManager runat="server" ID="scriptManager">
        </asp:ScriptManager>

Run the page again and fire the validation... oops... the client validation has gone =( We only have server validation. I'm not sure why this happens but my best guess is that the just added ScriptManager control is overriding our code settings.

To fix it, change the declaration of the ScriptManager control on the Site.master page to:

<asp:ScriptManager runat="server" ID="scriptManager1">
        <Scripts>
            <asp:ScriptReference Name="MsAjaxBundle" />
            <asp:ScriptReference Name="jquery" />
            <asp:ScriptReference Name="WebForms.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebForms.js" />
            <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebUIValidation.js" />
            <asp:ScriptReference Name="MenuStandards.js" Assembly="System.Web" Path="~/Scripts/WebForms/MenuStandards.js" />
            <asp:ScriptReference Name="GridView.js" Assembly="System.Web" Path="~/Scripts/WebForms/GridView.js" />
            <asp:ScriptReference Name="DetailsView.js" Assembly="System.Web" Path="~/Scripts/WebForms/DetailsView.js" />
            <asp:ScriptReference Name="TreeView.js" Assembly="System.Web" Path="~/Scripts/WebForms/TreeView.js" />
            <asp:ScriptReference Name="WebParts.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebParts.js" />
            <asp:ScriptReference Name="Focus.js" Assembly="System.Web" Path="~/Scripts/WebForms/Focus.js" />
            <asp:ScriptReference Name="WebFormsBundle" />
        </Scripts>
    </asp:ScriptManager>

Run the application and our little example will work again as expected

Sadly these new settings are the equivalent to the settings added by code and we need to add them to be able to use the traditional Microsoft AJAX controls.

There's one last thing we need to configure, this is because there's actually a bug with the ValidationSummary control.

To test it, update the Default.aspx page as follows:

<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <asp:TextBox runat="server" ID="txt" />
    <asp:RequiredFieldValidator ErrorMessage="txt is required" ControlToValidate="txt" runat="server" Text="*" Display="Dynamic" />
    <asp:Button Text="Send info" runat="server" />

Now run the page again, scroll down until you can see the button and click it... woot your page jumped to the top... the workaround to solve this little bug is to add the following code to the Site.master

<script>
            window.scrollTo = function () {

            };
        </script>

 



ASP.NET 4.5 Hosting - ASPHostPortal.com :: Uploading Several Data files Employing jQuery and Generic Handler in ASP.NET 4.5

clock December 5, 2014 09:11 by author Ben

This post describes the best way to upload numerous data files in ASP.NET Kinds using the jQuery and Generic Handler. Generally builders utilize the FileUpload Server management to add data files from the client device for the server that's rendered as as an Enter factor and set to file and helps you to pick out the file or various information. We can easily make use of the jQuery to help make an Ajax connect with towards the server and Submit the many picked documents for the Generic Handler as opposed to an entire webpage postback.

 


On this short article for creating the application, I am utilizing Visual Studio 2013 that has the framework 4.5.1. So, let us start with all the following course of action.

Creating WebForms

Step 1: Open Visual Studio and create the ASP.NET Web Application.

Step 2: Select the WebForms project template to proceed.

Visual Studio automatically creates the project and adds files and folders to the project by default.

Creating WebForm


Step 1: Just right-click on the project and add a new folder named "UploadedFiles".


Step 2: Just right-click on the project and add a new Web Form and replace the body content from the following content:

<form id="form1" runat="server">

    <h2>ASP.NET</h2>
    <p class="lead">Selcting Multiple Files using jQuery and Generic Handler</p>  

 

    <div class="form-group">
        <div>
            <asp:Label runat="server" AssociatedControlID="MultipleFilesUpload">Select Files</asp:Label>           
            <asp:FileUpload ID="MultipleFilesUpload" runat="server" AllowMultiple="true" />          

        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <asp:Button runat="server" ID="BtnUpload" Text="Upload Files" CssClass="btn btn-default" />
        </div>
    </div>  
 </form>


In the code above, I used the AllowMultiple property of FileUpload that is set to true. It is one of the HTML 5 features used in here.

Step 2: Now in the <head> section add the following code:

<script src="Scripts/jquery-1.10.2.js"></script>

<link href="Content/bootstrap.css" rel="stylesheet" />

<link href="Content/Site.css" rel="stylesheet" />

<script type="text/javascript">
    $(document).ready(function () {
        $("#BtnUpload").click(function (event) {
            var uploadfiles = $("#MultipleFilesUpload").get(0);
            var uploadedfiles = uploadfiles.files;
            var fromdata = new FormData();
            for (var i = 0; i < uploadedfiles.length; i++) {
                fromdata.append(uploadedfiles[i].name, uploadedfiles[i]);
            }
             var choice = {};
            choice.url = "UploadHandler.ashx";
            choice.type = "POST";
            choice.data = fromdata;
            choice.contentType = false;
            choice.processData = false;
            choice.success = function (result) { alert(result); };
            choice.error = function (err) { alert(err.statusText); };
            $.ajax(choice);
            event.preventDefault();
        });
    });
</script>

Via the code over, the data files are chosen inside the file upload handle working with the information residence of the DOM factor. the loop iterates by means of many of the information then calls the append() method of the FormData to incorporate the data files into the FormData item.

Now, the info is usually to be sent into the server. The £.ajax() is employed to transfer the information. The choice item supplies numerous options such as focus on URL and HTTP process. Now we have set the URL home on the GenericHandler file named UploadHandler.ashx . We now have established the contentType and processData home to phony with which the jQuery will not likely URL encode the info while sending into the server. The achievements and mistake properties are utilised to display the messages as a result of an warn.

Creating Generic Handler

Step 1: Add the Generic Handler by right-clicking on the project named UploadHandler.


Step 2: Modify the code with the following code:

namespace UploadMultipleFilesApp
{
    public class UploadHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.Files.Count > 0)
            {
                HttpFileCollection SelectedFiles = context.Request.Files;
                for (int i = 0; i < SelectedFiles.Count; i++)
                {
                    HttpPostedFile PostedFile = SelectedFiles[i];
                    string FileName = context.Server.MapPath("~/UploadedFiles/" + PostedFile.FileName);
                    PostedFile.SaveAs(FileName);                   
                }
            }
            else
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("Please Select Files");
            }
            context.Response.ContentType = "text/plain";
            context.Response.Write("Files Uploaded Successfully!!");
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

In this article we will see which the information which might be posted to your server and will be accessed using the Ask for object. Each individual element in the HttpFileCollection is of type HttpPostedFile. FileName property is utilized to receive the file identify of posted file and return it and also the similar name id used to conserve the file.

Run WebForm

Now run the webform and choose the files as shown below that the files are selected.


After clicking on Upload Files, the message is generated.


Summary

This article explained the best way to choose numerous information and add them utilizing jQuery and Generic Handler in ASP.NET Web Forms. Joyful Coding and thanks for looking at.

 



ASP.NET 4.5 Hosting - ASPHostPortal.com :: Add Multiple Files Utilizing ASP.NET 4.5

clock November 28, 2014 05:07 by author Ben

In earlier versions of ASP.NET (edition under ASP.NET 4.5), we didn't have any inbuilt functionality to add several files at the same time. ASP.NET FileUpload handle permits uploading just one file in a time. Alternate answers to add numerous files are third party controls like Telerik or Devexpress. We can also use various jQuery Plugin like Uploadify to attain comparable performance.


In ASP.NET 4.5, we can add multiple documents simultaneously making use of ASP.NET FileUpload control. In ASP.NET 4.5, FileUpload Control support HTML5 several attribute.

Under are the steps to add numerous information utilizing ASP.NET 4.5 :

  1. In Visual Studio 2012, In Visual Studio 2012, create a new website using .Net 4.5 framework.
  2. Add a new web form (for example FileUpload.aspx) in newly created website.
  3. In code-beside file of FileUpload.aspx, write following code for FileUpload Control:

<asp:fileupload AllowMultiple="true" id="MultipleFileUpload" runat="server">
</asp:fileupload>

In above code, I have set AllowMultiple property of FileUpload Control to true.

Add one button to upload multiple files using FileUpload Control on button click.

<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />

Write below code on button click event handler.

protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (MultipleFileUpload.HasFiles)
        {
            StringBuilder UploadedFileNames = new StringBuilder();

            foreach (HttpPostedFile uploadedFile in MultipleFileUpload.PostedFiles)
            {
                string FileName = HttpUtility.HtmlEncode(Path.GetFileName(uploadedFile.FileName));
                uploadedFile.SaveAs(System.IO.Path.Combine(Server.MapPath("~/Files/"), FileName));
                UploadedFileNames.AppendFormat("{0}<br />", FileName);
            }
            Response.Write("Uploaded Files are : <br/>" + UploadedFileNames);
        }
    }

On button click, I am checking for multiple files and saving those files into Files folder of web application.
Compile source code and run the website application.

 

I had selected five images to upload. Once I had clicked on Upload button, all five images were uploaded successfully in Files folder.



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