European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Get Started With React Using TypeScript and ASP.NET MVC 6?

clock April 4, 2016 20:18 by author Anthony

All of the major frameworks (Web API, forms, and MVC) have been rolled out under the umbrella of a single unified programming model. There’s a new built-in dependency framework, and there are Tag Helpers. All this has had a major impact on development. A lot has changed in the world of ASP.NET 5 and MVC 6. But In this tutorial, I will explain about how to get started with React using TypeScript and ASP.NET 5 MVC 6.

But before we start, there are few things you will need to install :

  • Microsoft Visual Studio 2015 (Community Edition is free and it’s open source!)
  • TypeScript (included in VS2015)
  • Node.js and NPM (included in VS2015


    Deprecated, use Typings:
  • Typings. Run npm install typings -g to install globally.
  • Webpack. Run npm install webpack -g to install globally.

 

Create a New ASP.NET MVC 6 Project

First create a new ASP.NET Web Application project. In the next dialog choose Empty template under ASP.NET 5 Templates. This is to keep things simple and we will only be adding add the stuff we actually need.

Install ReactJS.NET

Next you’ll need to modify your project.json file so open it up. To work with React in .NET we’ll be using a library called ReactJS.NET. It will allow you to do server side (or isomorphic) rendering which is cool but more on that later.

Before installing ReactJS.NET we’ll need to remove "dnxcore50": { } line from project.json to make it work. Then add "React.AspNet": "2.1.2" and "Microsoft.AspNet.Mvc": "6.0.0-rc1-final" under dependencies and save the file. Both ASP.NET MVC 6 and ReactJS.NET should get immediately installed.

Your project.json should now look something like this:

{
  "version": "1.0.0-*",
  "compilationOptions": {
    "emitEntryPoint": true
  },

  "dependencies": {
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    "React.AspNet": "2.1.2"
  },

  "commands": {
    "web": "Microsoft.AspNet.Server.Kestrel"
  },

  "frameworks": {
    "dnx451": { }
  },

  "exclude": [
    "wwwroot",
    "node_modules"
  ],
  "publishExclude": [
    "**.user",
    "**.vspscc"
  ]
}


Create a new folder called app under your project. This is where we’ll be hosting all our React components. Right-click that folder and add a new item. Search for a TypeScript JSX file template and name your file HelloWorld.tsx. Add the following lines.

/// <reference path="../../../typings/main/ambient/react/index.d.ts" />
import React = require('react');

// A '.tsx' file enables JSX support in the TypeScript compiler,
// for more information see the following page on the TypeScript wiki:
// https://github.com/Microsoft/TypeScript/wiki/JSX

interface HelloWorldProps extends React.Props<any> {
    name: string;
}

class HelloMessage extends React.Component<HelloWorldProps, {}> {
    render() {
        return <div>Hello {this.props.name}</div>;
    }
}
export = HelloMessage;

You’ll see that the react.d.ts cannot be resolved. To fix this you’ll need to run typings install react --ambient --save in the Package Manager console to install the TypeScript definitions for react. Visual Studio will still complain about the --module flag that must be provied. To fix this add a tsconfig.json in the app folder with the following content:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "jsx": "preserve"
  }
}

Note : If the JSX isn’t being generated make sure that you have enabled TypeScript compilation in Visual Studio. To do this check the Automatically compile TypeScript files which are not part of the project under Tools -> Options -> TypeScript -> Project -> General in Visual Studio.

 

Set Up Web Pack

We’ll be using Webpack although you could use any other module bundler as well. You should have installed Webpack already but if you haven’t check out the beginning of this post on how to do it.

In the app folder create index.js:

module.exports = {
    // All the components you'd like to render server-side
    HelloMessage: require('./HelloWorld')
};

This will be used to tell Webpack which components to bundle together for server and client side rendering. Right now we only have the HelloWorld component.

Next in your wwwroot folder add two files called client.js and server.js. They both share the same content for this project:


// All JavaScript in here will be loaded client/server -side.
// Expose components globally so ReactJS.NET can use them
var Components = require('expose?Components!./../app');

The last thing that’s left is a Webpack configuration file. Create webpack.config.js under your project:

var path = require('path');
module.exports = {
    context: path.join(__dirname, 'wwwroot'),
    entry: {
        server: './server',
        client: './client'
    },
    output: {
        path: path.join(__dirname, 'wwwroot/build'),
        filename: '[name].bundle.js'
    },
    module: {
        loaders: [
            // Transform JSX in .jsx files
            { test: /\.jsx$/, loader: 'jsx-loader?harmony' }
        ],
    },
    resolve: {
        // Allow require('./blah') to require blah.jsx
        extensions: ['', '.js', '.jsx']
    },
    externals: {
        // Use external version of React (from CDN for client-side, or
        // bundled with ReactJS.NET for server-side)
        react: 'React'
    }
};


Webpack will need some additional modules to do the bundling. Right-click the project and select “Add item”. In the dialog choose NPM Configuration file and name it package.json:

{
    "version": "1.0.0",
    "name": "ASP.NET",
    "private": true,
    "devDependencies": {
        "webpack": "1.12.9",
        "expose-loader": "0.7.1",
        "jsx-loader": "0.13.2"
    }
}


Once again saving the file will execute NPM and install the three packages.

Finally open command prompt and browse to the project’s folder (where webpack.config.js is located). Then type webpack, press enter and Webpack should beautifully build two JavaScript bundles under wwwroot/build. Of these client.bundle.js should be included client side and server.bundle.js should be included server side. Remember to run webpack each time you have modified your React components or add this step to your build process.

Add a controller and a view

Next, do the obvious thing of creating a controller and a view so that we can host our fancy React component somewhere. Create a folder called Controllers under the project and add a new controller called HomeController under the folder. The controller should have only one GET Index method like so:

using Microsoft.AspNet.Mvc;
namespace React.MVC6.Sample.Controllers
{
    public class HomeController : Controller
    {
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }
    }
}

After that add a folder called Views under the project. Under Views add a new folder called Shared. Create a layout file called _Layout.cshtml there with the following content:

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        @RenderBody()
    </div>
</body>
</html>

Then add a few defaults for our views. In the Views folder add a new file called _ViewImports.cshtml with just the following content. This will ensure that ReactJS.NET is by default available in all our views.

@using React.AspNet


Create another file called _ViewStart.cshtml under Views folder with this content:

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

Finally create a new folder called Home under Views and create a file called Index.cshtml in there. Place the following in there to render your React component with initial data:

@{
    ViewBag.Title = "Index";
}

<h1>Hello World</h1>

@Html.React("Components.HelloMessage", new { name = "Sam" })

<script src="https://fb.me/react-0.14.0.min.js"></script>
<script src="https://fb.me/react-dom-0.14.0.min.js"></script>
<script src="@Url.Content("/build/client.bundle.js")"></script>

@Html.ReactInitJavaScript()

Including the javascripts in the view like this isn’t very pretty but you’ll get the idea. The name that we pass to the component could as well come from a model passed down from the controller.

Configure the Web Application

Then we will need to make sure that ASP.NET MVC 6 and React get loaded properly when the application starts up. So open up your startup.cs file and replace the contents with this:

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.StaticFiles;
using Microsoft.Extensions.DependencyInjection;
using React.AspNet;

namespace React.MVC6.Sample
{
    public class Startup
    {
        // Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddReact(); // Add React to the IoC container
            services.AddMvc();
        }

        // Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app)
        {
            app.UseIISPlatformHandler();

            // Initialise ReactJS.NET. Must be before static files.
            app.UseReact(config =>
            {
                config
                    .SetReuseJavaScriptEngines(true)
                    .AddScriptWithoutTransform("~/build/server.bundle.js");
            });

            app.UseStaticFiles(new StaticFileOptions
            {
                ServeUnknownFileTypes = true
            });

            app.UseMvc(r =>
            {
                r.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" }
                );
            });
        }

        // Entry point for the application.
        public static void Main(string[] args) => WebApplication.Run<Startup>(args);
    }
}

 

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Create & Update Cookie in ASP.NET MVC?

clock March 30, 2016 23:25 by author Peter

Today, we will explain you about how to create and update cookie in ASP.NET MVC. An HTTP cookie (also called web cookie, Internet cookie, browser cookie or simply cookie), is a small piece of data sent from a website and stored in the user's web browser while the user is browsing. Every time the user loads the website, the browser sends the cookie back to the server to notify the user's previous activity. Cookies were designed to be a reliable mechanism for websites to remember stateful information (such as items added in the shopping cart in an online store) or to record the user's browsing activity (including clicking particular buttons, logging in, or recording which pages were visited in the past). Cookies can also store passwords and form content a user has previously entered, such as a credit card number or an address.

The output of the index.aspx runs over the Home Controller:
public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";
        string cookie = "There is no cookie!";
        if(this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Cookie"))
        {
            cookie = "Yeah - Cookie: " + this.ControllerContext.HttpContext.Request.Cookies["Cookie"].Value;
        }
        ViewData["Cookie"] = cookie;
        return View();
    }

Here it is detected if a cookie exists and if yes than it will be out given.
These two Links guide you to the CookieController:
public class CookieController : Controller
{

    public ActionResult Create()
    {
        HttpCookie cookie = new HttpCookie("Cookie");
        cookie.Value = "Hello Cookie! CreatedOn: " + DateTime.Now.ToShortTimeString();

        this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
        return RedirectToAction("Index", "Home");
    }

    public ActionResult Remove()
    {
        if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Cookie"))
        {
            HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Cookie"];
            cookie.Expires = DateTime.Now.AddDays(-1);
            this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
        }
        return RedirectToAction("Index", "Home");
    }

}


With the create method it´s quite simple to create a Cookie and lay it down into the response and afterwards it turns back to the Index View.

The remove method controls if a cookie exists and if the answer is positive the Cookie will be deleted directly.

Beware while deleting cookies:
This way to delete a cookie doesn´t work:
this.ControllerContext.HttpContext.Response.Cookies.Clear();


The cookie has to go back to the remove (like it is given in the Cookie Controller) and an expiry date should be given. I´m going to set it on yesterday so the browser has to refuse it directly.

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How To Use C# To Send Emails with Mail Helper

clock February 27, 2016 00:28 by author Rebecca

In this post, I will create simple mail helper class for sending emails in ASP.NET MVC using C#.

IMPLEMENTATION

Step 1

Create a class name MailHelper and the add the following code:

public class MailHelper
    {
        private const int Timeout = 180000;
        private readonly string _host;
        private readonly int _port;
        private readonly string _user;
        private readonly string _pass;
        private readonly bool _ssl;

        public string Sender { get; set; }
        public string Recipient { get; set; }
        public string RecipientCC { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
        public string AttachmentFile { get; set; }

        public MailHelper()
        {
            //MailServer - Represents the SMTP Server
            _host = ConfigurationManager.AppSettings["MailServer"];
            //Port- Represents the port number
            _port = int.Parse(ConfigurationManager.AppSettings["Port"]);
            //MailAuthUser and MailAuthPass - Used for Authentication for sending email
            _user = ConfigurationManager.AppSettings["MailAuthUser"];
            _pass = ConfigurationManager.AppSettings["MailAuthPass"];
            _ssl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSSL"]);
        }

        public void Send()
        {
            try
            {

// We do not catch the error here... let it pass direct to the caller
                Attachment att = null;
                var message = new MailMessage(Sender, Recipient, Subject, Body) { IsBodyHtml = true };
                if (RecipientCC != null)
                {
                    message.Bcc.Add(RecipientCC);
                }
                var smtp = new SmtpClient(_host, _port);

                if (!String.IsNullOrEmpty(AttachmentFile))
                {
                    if (File.Exists(AttachmentFile))
                    {
                        att = new Attachment(AttachmentFile);
                        message.Attachments.Add(att);
                    }
                }

                if (_user.Length > 0 && _pass.Length > 0)
                {
                    smtp.UseDefaultCredentials = false;
                    smtp.Credentials = new NetworkCredential(_user, _pass);
                    smtp.EnableSsl = _ssl;
                }

                smtp.Send(message);

                if (att != null)
                    att.Dispose();
                message.Dispose();
                smtp.Dispose();
            }

            catch (Exception ex)
            {
            }
        }
    }

Step 2

Place the following code in the app settings of your application:

appSettings>
<add key=”MailServer” value=”smtp.gmail.com”/>
<add key=”Port” value=”587″/>
<add key=”EnableSSL” value=”true”/>
<add key=”EmailFromAddress” value=”[email protected]”/>
<add key=”MailAuthUser” value=”[email protected]”/>
<add key=”MailAuthPass” value=”xxxxxxxx”/>
</appSettings>

Step 3

If you don’t have authentication for sending emails you can pass the emtpy string in MailAuthUser and MailAuthPass.

<appSettings>
<add key=”MailServer” value=”smtp.gmail.com”/>
<add key=”Port” value=”587″/>
<add key=”EnableSSL” value=”true”/>
<add key=”EmailFromAddress” value=”[email protected]”/>
<add key=”MailAuthUser” value=””/>
<add key=”MailAuthPass” value=””/>
</appSettings>

USAGE

Add the following code snippet in your controller to call Mail Helper class for sending emails:

var MailHelper = new MailHelper
   {
      Sender = sender, //email.Sender,
      Recipient = useremail,
      RecipientCC = null,
      Subject = emailSubject,
      Body = messageBody
   };
 MailHelper.Send();

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How To Perform CSV Files (Upload & Read) in ASP.NET MVC

clock February 20, 2016 00:39 by author Rebecca

To read CSV file doesn’t mean to use String.Split(). CSV files may contain commas, carriage returns, speechmarks…etc within strings. In this post, we will learn how to upload and read CSV File in ASP.NET MVC WITHOUT using Jet/ACE OLEDB provider. It is helpful when you have to deploy your code on shared hosting, Azure website or any server where ACE Database engine is not available. In this post, we will use a fast CSV Reader.

Step 1

Create ASP.NET MVC Empty Project

Step 2

To install CSVReader, run the following command in the Package Manager Console:

Install-Package LumenWorksCsvReader

Step 3

Add New Controller say HomeController and add following action:

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

Step 4

Add View of Upload action and use following code:

@model System.Data.DataTable
@using System.Data;
 
<h2>Upload File</h2>
 
@using (Html.BeginForm("Upload", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()   
    @Html.ValidationSummary()
    
    <div class="form-group">
        <input type="file" id="dataFile" name="upload" />
    </div>
    
    <div class="form-group">
        <input type="submit" value="Upload" class="btn btn-default" />
    </div>
    
    if (Model != null)
    {
        <table>
            <thead>
                <tr>
                    @foreach (DataColumn col in Model.Columns)
                    {        
                        <th>@col.ColumnName</th>
                    }
                </tr>
            </thead>
            <tbody>
                @foreach (DataRow row in Model.Rows)
                {       
                    <tr>
                        @foreach (DataColumn col in Model.Columns)
                        {            
                            <td>@row[col.ColumnName]</td>
                        }
                    </tr>
                }
            </tbody>
        </table>
    }
}

We will read CSV file, get data in DataTable and show DataTable in View.

Step 5

Here's how to read submitted CSV file:

[HttpPost]
[ValidateAntiForgeryToken]
 public ActionResult Upload(HttpPostedFileBase upload)
{
    if (ModelState.IsValid)
    {
 
        if (upload != null && upload.ContentLength > 0)
        {                  
 
            if (upload.FileName.EndsWith(".csv"))
            {
                Stream stream = upload.InputStream;
                DataTable csvTable = new DataTable();
                using (CsvReader csvReader =
                    new CsvReader(new StreamReader(stream), true))
                {
                    csvTable.Load(csvReader);
                }
                return View(csvTable);
            }
            else
            {
                ModelState.AddModelError("File", "This file format is not supported");
                return View();
            }
        }
        else
        {
            ModelState.AddModelError("File", "Please Upload Your file");
        }
    }
    return View();
}

It is assumed the file will have column names in first row.

Output

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Connect an MVC Project to an SQL database?

clock February 18, 2016 19:59 by author Peter

I'm simply getting to grips with MVC linq etc and came across what sounds like a standard stumbling block. All the tutorials are either Code first examples or they create the information from scratch within the App_Data directory. All well and smart for a tutorial that require to be simply moveable to the readers computer, however not very useful when putting in a full scale MVC application. My first problem was my lack of knowledge of Linq to SQL. Finally, how to add an external SQL database to your MVC project:

  • Right click on "Models" folder, choose "Add New Item"
  • Add a "Link to SQL Classes" item
  • Open your "Server Explorer" pane (if you cant see it attempt "View" on the menu bar and "Server Explorer"
  • Right click on "Data Connections" and choose "Add Connection"
  • Follow the instructions.
  • almost there....
  • Expand your newly added database to look at the tables.
  • Drag the tables you wish over to the main pane of the "Link to SQL Classes" item you added at the start.
  • Hey presto, you have a database context you'll run Linq queries against.

Please bear in mind you will need to use the "Models" namespace to reference you database context objects.
And now back to highly sophisticated programming!

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How To Use ASP.NET MVC To Increase Website Performance

clock February 12, 2016 23:50 by author Rebecca

In this tutorial, we will discuss about how you can increase the performance of website using ASP.NET MVC.

1. Remove Unused view engines

protected void Application_Start()
{
    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(new RazorViewEngine());
}

2. Deploying Production Code in Release Mode

Make sure your production application always runs in release mode in the web.config
<compilation debug=”false”></compilation>

<configuration> <system.web> <deployment retail=”true”></deployment> </system.web> </configuration>

3. Use OutputCacheAttribute When Appropriate

MVC will not do any View Look-up Caching if you are running your application in Debug Mode

[OutputCache(VaryByParam = "none", Duration = 3600)]
public ActionResult Categories()
{
    return View(new Categories());
}

4. Use HTTP Compression

Add gzip (HTTP compression) and static cache (images, css, …) in your web.config:

<system.webserver><urlcompression dodynamiccompression=”true” dostaticcompression=”true” dynamiccompressionbeforecache=”true”></urlcompression>
</system.webserver>

5. Add an Expires or a Cache-Control Header

<configuration><system.webServer>
<staticContent>
<clientCache cacheControlMode=”UseExpires”
httpExpires=”Mon, 06 May 2013 00:00:00 GMT” />
</staticContent>
</system.webServer>
</configuration>

6. Uncontrolled Actions

protected override void HandleUnknownAction(string actionName)
{
       RedirectToAction("Index").ExecuteResult(this.ControllerContext);
}

7. Other Ways

  • Avoid passing null models to views
  • Remove unused HTTP Modules
  • Put repetitive code inside your PartialViews
  • Put Stylesheets at the Top
  • Put Scripts at the Bottom
  • Make JavaScript and CSS External
  • Minify JavaScript and CSS
  • Remove Duplicate Scripts
  • No 404s
  • Avoid Empty Image src
  • Use a Content Delivery Network
  • Use either Microsoft, Google CDN for referencing the Javascript or Css libraries
  • Use GET for AJAX Requests
  • Optimize Images

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Generate URLs with ASP.NET MVC

clock February 4, 2016 20:38 by author Peter

I have been operating with ASP.NET MVC for some time and yet I still had trouble making an attempt to get a URL in a view. URL generation is particularly important for ASP.NET MVC as a result of it uses a routing engine to map URLs to code. If we hard code a URL then we lose the ability to later vary our routing scheme. I have found 2 ways that currently (ASP.NET MVC preview 2) work to generate URLs in a view. the first uses the GetVirtualPath method and seems overly complicated - thus I wrapped it in a global helper:

public static string GenerateUrl(HttpContext context, RouteValueDictionary routeValues)
    {
        return RouteTable.Routes.GetVirtualPath(
            new RequestContext(new HttpContextWrapper2(context), new RouteData()),
            routeValues).ToString();
    }


But then I found that I could achieve a similar result additional simply using UrlHelper, accessible via the URL property of the view.
// link to a controller
Url.Action("Home");

// link to an action
Url.Action("Home", "Index");

// link to an action and send parameters
Url.Action("Edit", "Product", new RouteValueDictionary(new { id = p.Id }));


Or, if you want the url for a hyperlink you can get that in one step using the ActionLink method on the Html property:
Html.ActionLink<HomeController>(c => c.Index(),"Home")

So I no longer see a need for my GenerateUrl method and have removed it from my helper. All of this would be much easier if there was some documentation. Im sure there is a better way so if you can think of an improvement please leave it in the comments.

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How To Show The Progress of The Controller

clock January 22, 2016 23:52 by author Rebecca

Sometimes, the controller actions can trigger a long running background process. For example, when the user clicks a link in the page, a word document is generated in the background, and the properties of the word document is shown in the subsequent page. Generation of word documents can take anywhere between 3 seconds to 30 seconds. During this time, the user needs some feedback about the progress of the operation. This post shows how you can provide progress information to the page which triggered the long running background process.

Step 1

Consider a MVC application with two pages: Index.cshtml and Generate.cshtml. The Index.cshtml has a link - Generate. When the user clicks the link, the Generate page is shown. The Generate action is a long running operation that happens in the background. To execute long running operations from a MVC controller, we derive the controller from AsyncController. The following code snippet shows the HomeController with the background operations:

public class HomeController : AsyncController
{
    //
    // GET: /Home/

    private BackgroundWorker worker = default(BackgroundWorker);
    private static int progress = default(int);

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

    public void GenerateAsync()
    {
        worker = new BackgroundWorker();
        worker.WorkerReportsProgress = true;
        worker.DoWork += worker_DoWork;
        worker.ProgressChanged += worker_ProgressChanged;
        AsyncManager.OutstandingOperations.Increment();
        worker.RunWorkerAsync();
    }

    void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progress = e.ProgressPercentage;
    }

    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        for (int i = 0; i < 100; i++)
        {
            Thread.Sleep(300);
            worker.ReportProgress(i+1);
        }

        AsyncManager.OutstandingOperations.Decrement();
    }

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

    public ActionResult GetProgress()
    {
        return this.Json(progress, JsonRequestBehavior.AllowGet);
    }
}

The three main action methods in the above controller are - Index(), GenerateAsync(), GetProgress(). Index() displays the Index page. GenerateAsync() triggers the background operation. The background operation loops 100 times and sleeps for 300 ms in each iteration. At the end of each iteration, it reports progress as a percentage.

Step 2

The GetProgress() action gets the reported progress which is stored as a static variable. The GetProgress() is triggered when the user clicks the link. The javascript in the Index page shows how the GetProgress() action method is called:

$(document).ready(
    function () {
        $("#genLink").click(
            function (e) {
                setInterval(
                    function () {
                        $.get("/Home/GetProgress",
                            function (data) {
                                $("#progress").text(data);
                        });
                    }, 1000);
            });
    });

Here's the HTML

<body>
    <h1>Progress</h1>
    <h2 id="progress"></h2>
    <div>
        @Html.ActionLink("Generate", "Generate", null,
            new { id = "genLink" })
    </div>
</body>

On clicking the link, you have caledl the setInterval() function that is triggered every second. In the recurring function, we call the action method - GetProgress(). You have displayed the progress data in the page in the progress tag.

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Moving Your Data From ListBox to other ListBox with JQuery in ASP.NET MVC

clock October 30, 2015 00:48 by author Peter

Now, we will discussed about Moving Your Data From ListBox to other ListBox with JQuery in ASP.NET MVC. A list box is a graphical control element that allows the user to select one or more items from a list contained within a static, multiple line text box. First step, write the following code:
namespace Mvc2.Controllers
{
public class MovieController : Controller
{
    public ActionResult MoveDateinListBox()
  {
      return View();
  }
  }
}

In View
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
MoveDateinListBox
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h5>
    MVC:How to Move data between two ListBoxes using JQuery</h5>
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
<script language="javascript" type="text/javascript">
    $(function () {
        $("#MoveToRight,#MoveToLeft").click(function (event) {
            var id = $(event.target).attr("id");
            var selectFrom = id == "MoveToRight" ? "#SelectLeftItem" : "#SelectRightItem";
            var moveTo = id == "MoveToRight" ? "#SelectRightItem" : "#SelectLeftItem";
            var selectedItems = $(selectFrom + " option:selected").toArray();
            $(moveTo).append(selectedItems);
            selectedItems.remove;
        });
    });
</script>
<form method="get" action="" runat="server">
 <select id="SelectLeftItem" multiple="multiple" style="height: 100px">
    <option value="1">ASP.NET</option>
    <option value="2">C#.NET</option>
    <option value="3">SQL Server</option>
    <option value="4">VB.NET</option>
</select>
<input id="MoveToRight" type="button" value=" >> " style="font-weight: bold" />
<input id="MoveToLeft" type="button" value=" << " style="font-weight: bold" />
<select id="SelectRightItem" multiple="multiple" style="height: 100px">
    <option value="1">MVC</option>
    <option value="2">WCF</option>
    <option value="3">WPF</option>
    <option value="4">Silverlight</option>
</select>
</form>
</asp:Content>


And here is the output:

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting France - HostForLIFE.eu :: How To Clear Thumbnails After It Has Uploaded

clock October 24, 2015 00:23 by author Rebecca

Sometimes, we need to clear the thumbnails from dropzone.js after the file is uploaded. In this article, I will tell you how to do it.

You need to call addedfile function once the file is uploaded. After that, you have to to generate remove button for the thumbnail.

Look at this example code:

Step 1: File Upload response from the server

Dropzone.options.dropzoneForm = {
maxFiles: 2,
init: function () {
this.on("maxfilesexceeded", function (data) {
var res = eval('(' + data.xhr.responseText + ')');

});
this.on("addedfile", function (file) {

Step 2: Create the remove/clear button

var removeButton = Dropzone.createElement("
<button>Remove file</button>
");

Step 3: Capturing the Dropzone.js instance as closure

var _this = this;

Step 4: Listen to the click event

removeButton.addEventListener("click", function (e) {

Make sure the button click doesn't submit the form:

e.preventDefault();
e.stopPropagation();

Step 5: Remove the file preview

_this.removeFile(file);

If you want to the delete the file on the server as well, you can do the AJAX request here:

});

Step 6: Add the button to the file preview element

file.previewElement.appendChild(removeButton);
});
}
};

That's it! Simple right?

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in