European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Authenticate HTML files with ASP.NET MVC ?

clock June 26, 2015 08:08 by author Peter

Today, let me explain about how to Authenticate HTML files with ASP.NET MVC. To Check Html URL is Authenticated or Not Using Asp.net/MVC using the following code:
Coding:
if (Request.RawUrl.ToLower().EndsWith(".html")) 

if (Request.Cookies[".ASPXAUTH"] != null) 

  string value = Request.Cookies[".ASPXAUTH"].Value; 
  if (value == null || value == "") 
  { 
     Response.Redirect("~/Account/LogOn"); 
  } 

else 

  Response.Redirect("~/Account/LogOn"); 

}

The .ASPXAUTH is the Form Authentication Cookies and Account is the Controller. The LogOn is the action. Next step, write the following code in webconfig section:
<buildProviders> 
<add extension=".html" type="System.Web.Compilation.PageBuildProvider" /> 
<add extension=".htm" type="System.Web.Compilation.PageBuildProvider" /> 
</buildProviders> 

<handlers> 
<add name="HTML" path="*.html" verb="GET, HEAD, POST, DEBUG" type="System.Web.UI.PageHandlerFactory" resourceT
ype="Unspecified" requireAccess="Script" /> 
<add name="HTM" path="*.htm" verb="GET, HEAD, POST, DEBUG" type="System.Web.UI.PageHandlerFactory" resourceTyp
e="Unspecified" requireAccess="Script" /> 
</handlers>  

I hope it works for you! Happy coding.

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 Dropzone.js and HTML to Upload File in ASP.NET MVC

clock June 26, 2015 06:19 by author Rebecca

In this article, you can learn how to file upload in ASP.NET MVC using Dropzone.js and HTML5. Dropzone.js is an open source library that provides drag and drop file uploads with image previews. It’s lightweight, doesn’t depend on any other library (like jQuery) and is highly customizable. Follow these steps to upload your file using Dropzone.js and HTML.

Step 1

Before jumping to the project, first you will download the Dropzone.js files. You can download the latest version from the official site here http://www.dropzonejs.com/ and also you can install using the nuget package manage console by the following command Package Manager Console:

PM> Install-Package dropzone

In this tutorial, I'm using the nuget command to install Dropzone.js:

Step 2

Next is file upload implementation. You have to create a default ASP.NET MVC Web Application after you have installed the Dropzone.js. Then, create a bundle for your script file in BundleConfig.cs:

bundles.Add(new ScriptBundle("~/bundles/dropzonescripts").Include(
                     "~/Scripts/dropzone/dropzone.js"));

Step 3

Similarly you can add the Dropzone stylesheet in the BundleConfig.cs:

bundles.Add(new StyleBundle("~/Content/dropzonescss").Include(
                     "~/Scripts/dropzone/css/basic.css",
                     "~/Scripts/dropzone/css/dropzone.css"));

Step 4

Now add the bundle reference in your _Layout page:

Step 5

Everything is fine, you can start writing up the application code. Now go to /Home/Index.cshtml file and Dropzone form in the page using this code:

div class="jumbotron">
    <form action="~/Home/SaveUploadedFile" method="post" enctype="multipart/form-data" class="dropzone" id="dropzoneForm" style="width: 50px; background: none; border: none;">
        <div class="fallback">
            <input name="file" type="file" multiple />
            <input type="submit" value="Upload" />
        </div>
    </form>
</div>

Step 6

Now open the HomeController.cs and add the following code as follows:

public ActionResult SaveUploadedFile()
        {
            bool isSavedSuccessfully = true;
            string fName = "";
                    try{
            foreach (string fileName in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[fileName];
                //Save file content goes here
                fName = file.FileName;
                if (file != null && file.ContentLength > 0)
                {

                    var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\WallImages", Server.MapPath(@"\")));

                    string pathString = System.IO.Path.Combine(originalDirectory.ToString(), "imagepath");

                    var fileName1 = Path.GetFileName(file.FileName);

                    bool isExists = System.IO.Directory.Exists(pathString);

                    if (!isExists)
                        System.IO.Directory.CreateDirectory(pathString);

                    var path = string.Format("{0}\\{1}", pathString, file.FileName);
                    file.SaveAs(path);

                }

            }
                       
           }
           catch(Exception ex)
            {
                isSavedSuccessfully = false;
            }


            if (isSavedSuccessfully)
            {
                return Json(new { Message = fName });
            }
            else
            {
                return Json(new { Message = "Error in saving file" });
            }
        }

Step 7

Then, add the following script to your Index.cshtml page:

//File Upload response from the server
        Dropzone.options.dropzoneForm = {
            init: function () {
                this.on("complete", function (data) {
                    //var res = eval('(' + data.xhr.responseText + ')');
                     var res = JSON.parse(data.xhr.responseText);
                });
            }
        };

Also add the following css:

#dropZone {
        background: gray;
        border: black dashed 3px;
        width: 200px;
        padding: 50px;
        text-align: center;
        color: white;
    }

Now, you have uploaded your file using Dropzone.js and HTML5.

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 Deploy Google ReCAPTCHA in ASP.NET MVC

clock June 22, 2015 06:48 by author Rebecca

Here in this tutorial, I will explain about how to use Google reCAPTCHA in ASP.NET MVC. 

What is reCAPTCHA? reCAPTCHA protects the websites you love from spam and abuse. Google has updated thier reCAPTCHA API  to 2.0 . Now, users can now attest they are human without having to solve a CAPTCHA. Instead with just a single click they’ll confirm they are not a robot and it is called as “No CAPTCHA reCAPTCHA“.  This is how new reCAPTCHA look as follows:

Getting Google ReCAPTCHA

Now, lets create an API key pair for your site at https://www.google.com/recaptcha/intro/index.html and click on Get reCAPTCHA at top of the page and follow the below steps to create an application.

 

Once you have done with registration, the following keys will be generated:

  • Site key : is used to display the widget in your page or code.
  • Secret key: can be used as communication between your site and Google to verify the user response whether the reCAPTCHA is valid or not.

The next is to display the reCAPTCHA widget in your site.

Displaying Widget

We can render the Google reCAPTCHA widget in two ways as:

  1.     Automatically render the widget
  2.     Explicitly render the widget

For this example we will use Automatically render the widget in your page.

First load the script reference:

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

Now, you need generate a DIV element with class name as g-recaptcha and your site key in the data-site key attribute in your webpage to generate reCAPTCHA.

<div class="g-recaptcha" data-sitekey="your_site_key"></div>

Now, implement above code in Home/Index.cshtml view page.

<div class="row">
    <div class="col-md-12">
        <form action="/home/validatecaptcha" method="POST">
            <div class="g-recaptcha" data-sitekey="6LfiS_8SAAAAABvF6ixcyP5MtsevE5RZ9dTorUWr"></div>
            <br />
            <input type="submit" value="Submit">
        </form>
    </div>

 
</div>
@section scripts{
   <script src="https://www.google.com/recaptcha/api.js" async defer></script>
}

Verifying User Response

Once reCAPTCHA is generated  and solved by a end user, a field with g-recaptcha-response will be populated in the html. When ever user submit the form on your site, you can POST the parameter g-recaptcha-response to verify the user response. The following API url is used to verify the user response.

https://www.google.com/recaptcha/api/siteverify?secret=your_secret&response=response_string&remoteip=user_ip_address

In above API url the secret and response parameters are required and where as remoteip is optional. Here secret represents the Secret Key that was generated in the key pair and the repsonse is the g-recaptcha-response that was submitted during the form post. The following is the API JSON response object that we get once the response is submitted.

{
  "success": true|false,
  "error-codes": [...]   // optional
}

Next, you will create an response class to verify the user response:

public class CaptchaResponse
{
    [JsonProperty("success")]
    public bool Success { get; set; }

    [JsonProperty("error-codes")]
    public List<string> ErrorCodes { get; set; }
}

Then, you can create a POST method in Index action in the Home controller to verify the user response.

[HttpPost]
public ActionResult ValidateCaptcha()
{
    var response = Request["g-recaptcha-response"];
    //secret that was generated in key value pair
    const string secret = "YOUR KEY VALUE PAIR";

    var client = new WebClient();
    var reply =
        client.DownloadString(
            string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, response));

    var captchaResponse = JsonConvert.DeserializeObject<CaptchaResponse>(reply);

    //when response is false check for the error message
    if (!captchaResponse.Success)
    {
        if (captchaResponse.ErrorCodes.Count <= 0) return View();

        var error = captchaResponse.ErrorCodes[0].ToLower();
        switch (error)
        {
            case ("missing-input-secret"):
                ViewBag.Message = "The secret parameter is missing.";
                break;
            case ("invalid-input-secret"):
                ViewBag.Message = "The secret parameter is invalid or malformed.";
                break;

            case ("missing-input-response"):
                ViewBag.Message = "The response parameter is missing.";
                break;
            case ("invalid-input-response"):
                ViewBag.Message = "The response parameter is invalid or malformed.";
                break;

            default:
                ViewBag.Message = "Error occured. Please try again";
                break;
        }
    }
    else
    {
        ViewBag.Message = "Valid";
    }

    return View();
}

That's all! Hope it works for you!

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 Return JavaScript Content from The Controller

clock June 19, 2015 06:50 by author Rebecca

In this tutorial, we're gonna discuss about how to return JavaScript Content from controller action method. I have created a demonstration here, let's follow it step by step.

Step 1

Create a controller action method that returns a view:

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

View for above action method:

@{
    ViewBag.Title = "OutputJavaScript";
}

<h2>OutputJavaScript</h2>

Try clicking on the link below <br />

@Html.ActionLink("Test JavaScript", "OutputJavaScriptAlert)

Step 2

The view appears in the browser like below:

Notice the 2nd parameter of the ActionLink method, this is the action method name of the controller. When the link “Test JavaScript” is clicked, it calls the OutputJavaScriptAlert action method of the controller.

Step 3

Controller code:

public JavaScriptResult OutputJavaScriptAlert()
  {
      string a = "alert('this is alert')";
      return JavaScript(a);
  }


This action method returns JavaScript content that we get it in the new window or to download as displayed in the above picture (depending on the browser).

In general, these methods are used in the Ajax methods to return partial content.

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 Validate Input in ASP.NET MVC ?

clock June 18, 2015 08:37 by author Peter

When you develop an app, sometimes your requirements could be that you need to send HTML values from view to the controller. Sometimes, we tend to use HTML Editors to save lots of some information into the view. By default, ASP.NET MVC does not permit a user to submit the HTML content. thus let's have a look at how to submit your form with HTML content.

First step, Open Visual Studio, then choose "New Project", then choose ASP.NET MVC Apps.

Name it the project name, then click OK.

Now, select Internet Application, then click OK.

Next step, make a new Model
ValidateModel.cs
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ValidateInputDemo.Models
{
    public class ValidateModel
    {
        public string description { get; set; }
    }
}

HomeController.cs
public ActionResult ValidateInput()
{
    return View();
}
[HttpPost]
public ActionResult  ValidateInput(string description)
{
    ValidateModel validateInputModel = new ValidateModel();
    validateInputModel.description = description;
    return View(validateInputModel);
}

Add a new method to your Controller

ValidateInput.cshtml
@model ValidateInputDemo.Models.ValidateModel
@{
       ViewBag.Title = "ValidateInput";
}
@using (@Html.BeginForm("ValidateInput","Home",
FormMethod.Post, new { @id = "form1", @enctype = "multipart/form-data" }))
{
    <label id="lblDescription">Description

     @Html.TextAreaFor(m=>m.description, new {@id="txtDescription",@name="description" })

    <input type="submit" id="bttn_Submit" />
}


You can see in the code above, there is a text area and a submit button, have a glance within the browser. Press F5.

You'll be able to see in the preceding screen, if you type one thing into the description and press Submit then nothing happens.

Now check the following example. Add HTML content into text area.

You'll get the error higher than. This error comes because this is often the security from ASP.NET MVC. For applications, a user cannot send HTML values to the controller, but sometimes we wish to send values to the controller. For resolving this issue, we've the ValidateInput(false) attribute. simply place this into your controller and have a look.
[HttpPost]
[ValidateInput(false)]
public ActionResult  ValidateInput(string description)
{
   ValidateModel validateInputModel = new ValidateModel();
   validateInputModel.description = description;
   return View(validateInputModel);
}

Now press F5. After filling in the HTML attribute press the submit button, you will never get an error. So when you want to work with HTML attributes in your app text area or textboxes, remember to use validateinpute(false) in your ActionMethod.

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 HTML Helper to Generate a DropDownList in ASP.NET MVC

clock June 15, 2015 07:24 by author Rebecca

A dropdownlist in MVC is a collection of SelectListItem objects. Depending on your project requirement you may either hard code the values in code or retrieve them from a database table. In this tutorial, I will show you how to generate a dropdownlist using DropDownList html helper based on both approaches.

Generating a DropDownList using Hard Coded Values

You will use the following overloaded version of "DropDownList" HTML helper.
DropDownList(string name, IEnumerable<SelectListItem> selectList, string optionLabel)

The following code will generate a departments dropdown list. The first item in the list will be "Select Department".
@Html.DropDownList("Departments", new List<SelectListItem>
{
    new SelectListItem { Text = "IT", Value = "1", Selected=true},
    new SelectListItem { Text = "HR", Value = "2"},
    new SelectListItem { Text = "Payroll", Value = "3"}
}, "Select Department")

The downside of hard coding dropdownlist values with-in code is that, if we have to add or remove departments from the dropdownlist, the code needs to be modified.

Retrieve DropDownList from A Database Table

Pass list of Departments from the controller, then store them in "ViewBag"

public ActionResult Index()
{
    // Connect to the database
    SampleDBContext db = new SampleDBContext();
    // Retrieve departments, and build SelectList
    ViewBag.Departments = new SelectList(db.Departments, "Id", "Name");
           
    return View();
}

Now in the "Index" view, you can access Departments list from "ViewBag"
@Html.DropDownList("Departments", "Select Department")

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 Detect Errors in View at ASP.NET MVC

clock June 12, 2015 08:49 by author Rebecca

In this tutorial, I will tell you about detecting errors in views at compile-time rather than at run-time.

The following code will display employee's FullName and Gender. Here we are working with a strongly typed view. Employee is the model class for this view. This class has got "FullName" and "Gender" properties.

@model MVCDemo.Models.Employee
<fieldset>
    <legend>Employee</legend>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.FullName)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.FullName)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.Gender)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Gender)
    </div>
</fieldset>

For example, if you mis-spell FullName property as shown below, and when you compile the project, you wouldn't get any compile time errors.

@Html.DisplayNameFor(model => model.FullName1)

You will only come to know, about the error when the page crashes at run-time. If you want to enable compile time error checking for views in MVC, please folow this step:

1. Open MVC project file using a notepad. Project files have the extension of .csproj or .vbproj
2. Search for MvcBuildViews under PropertyGroup. MvcBuildViews is false by default. Turn this to true as shown below.
<MvcBuildViews>true</MvcBuildViews>
3. Save the changes.

If you now build the project, you should get compile time error.

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.



Free ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Create a Star Rating in ASP.NET MVC

clock May 29, 2015 06:41 by author Rebecca

Members rating plays a vital role in deciding whether a product or services should be bought or not. In this article, you are going to learn how to create a star rating system in ASP.NET MVC.

Database structure

There are two small changes needed in our database for this rating system

1.  Add a field called "Votes" (or "Rating" whatever best suits you) in the existing database table where we are going to save other data of the post.

2. Add another database table called "VoteLog" that will save each vote details. Below are details of each field of this table.

  • AutoId - auto increment
  • SectionId - id of different sections of the website (we might be interested in implementing this rating system in multiple sections of the website, so all rating details will be saved into this database table)
  • VoteForId - unique id of the record for which member has rated
  • UserName - username of the member who has rated
  • Vote - rate given by a member for this post
  • Active -whether this record is active and should be counted

Different status of Rating control

Status 1 - When a visitor is visiting the website

Status 2 - When a visitor has logged in (is a member of the website)

Status 3 - After rating the post

Status 4 - When a visitor had rated the post and coming back to the same post again and browser cookie is still present in visitors' machine.

Status 5 - When a visitor had voted and browser cookies are cleared and he/she tried to vote again for the same post.

Lets start to create the Star Rating system

Step 1

Create a partial view named _VoteNow.cshtml in the Views/Shared folder and copy-paste below code.

@model string
@{
    var url = Request.Url.AbsolutePath;   
}
@if (!User.Identity.IsAuthenticated)
{
    <text>Please <a href="/Account/[email protected]" title="Login to rate">Login</a> to rate</text>
    return;
}
@if (Request.Cookies[url] == null) {
    <div id="ratingDiv" class="smallText"> Poor
        <img src="/images/whitestar.gif" alt="" class="ratingStar" data-value="1" /><img src="/images/whitestar.gif" alt="" class="ratingStar" data-value="2" /><img src="/images/whitestar.gif" alt="" class="ratingStar" data-value="3" /><img src="/images/whitestar.gif" alt="" class="ratingStar" data-value="4" /><img src="/images/whitestar.gif" alt="" class="ratingStar" data-value="5" /> Excellent
        <label id="lblResult"></label>
    </div>
    <style type="text/css">
        .ratingStar {
            cursor:pointer;
        }
    </style>
    <script type="text/javascript">
        var clickedFlag = false;
        $(".ratingStar").mouseover(function () {
            $(this).attr("src", "/images/yellowstar.gif").prevAll("img.ratingStar").attr("src", "/images/yellowstar.gif");
        });
        $(".ratingStar, #radingDiv").mouseout(function () {
            $(this).attr("src", "/images/whitestar.gif");
        });
        $("#ratingDiv").mouseout(function () {
            if (!clickedFlag)
            {
                $(".ratingStar").attr("src", "/images/whitestar.gif");
            }
        });
        $(".ratingStar").click(function () {
            clickedFlag = true;
            $(".ratingStar").unbind("mouseout mouseover click").css("cursor", "default");

            var url = "/Home/SendRating?r=" + $(this).attr("data-value") + "&s=5&id=@Model&url=@url";
            $.post(url, null, function (data) {
                $("#lblResult").html(data);
            });
        });
        $("#lblResult").ajaxStart(function () {
            $("#lblResult").html("Processing ....");
        });
        $("#lblResult").ajaxError(function () {
            $("#lblResult").html("<br />Error occured.");
        });
    </script>
}else{
    <text><span style="color:green;">Thanks for your vote !</span></text>
}


Step 2

Create a SendRating action method in HomeController.

public JsonResult SendRating(string r, string s, string id, string url)
        {
            int autoId = 0;
            Int16 thisVote = 0;
            Int16 sectionId = 0;
            Int16.TryParse(s, out sectionId);
            Int16.TryParse(r, out thisVote);
            int.TryParse(id, out autoId);
           
            if (!User.Identity.IsAuthenticated)
            {
                return Json("Not authenticated!");
            }

            if (autoId.Equals(0))
            {
                return Json("Sorry, record to vote doesn't exists");
            }

            switch (s)
            {
                case "5" : // school voting
                    // check if he has already voted
                    var isIt = db.VoteModels.Where(v => v.SectionId == sectionId &&
                        v.UserName.Equals(User.Identity.Name, StringComparison.CurrentCultureIgnoreCase) && v.VoteForId == autoId).FirstOrDefault();
                    if (isIt != null)
                    {
                        // keep the school voting flag to stop voting by this member
                        HttpCookie cookie = new HttpCookie(url, "true");
                        Response.Cookies.Add(cookie);
                        return Json("<br />You have already rated this post, thanks !");
                    }

                    var sch = db.SchoolModels.Where(sc => sc.AutoId == autoId).FirstOrDefault();
                    if (sch != null)
                    {
                        object obj = sch.Votes;

                        string updatedVotes = string.Empty;
                        string[] votes = null;
                        if (obj != null && obj.ToString().Length > 0)
                        {
                            string currentVotes = obj.ToString(); // votes pattern will be 0,0,0,0,0
                            votes = currentVotes.Split(',');
                            // if proper vote data is there in the database
                            if (votes.Length.Equals(5))
                            {
                                // get the current number of vote count of the selected vote, always say -1 than the current vote in the array
                                int currentNumberOfVote = int.Parse(votes[thisVote - 1]);
                                // increase 1 for this vote
                                currentNumberOfVote++;
                                // set the updated value into the selected votes
                                votes[thisVote - 1] = currentNumberOfVote.ToString();
                            }
                            else
                            {
                                votes = new string[] { "0", "0", "0", "0", "0" };
                                votes[thisVote - 1] = "1";
                            }
                        }
                        else
                        {
                            votes = new string[] { "0", "0", "0", "0", "0" };
                            votes[thisVote - 1] = "1";
                        }

                        // concatenate all arrays now
                        foreach (string ss in votes)
                        {
                            updatedVotes += ss + ",";
                        }
                        updatedVotes = updatedVotes.Substring(0, updatedVotes.Length - 1);

                        db.Entry(sch).State = EntityState.Modified;
                        sch.Votes = updatedVotes;
                        db.SaveChanges();

                        VoteModel vm = new VoteModel()
                        {
                            Active = true,
                            SectionId = Int16.Parse(s),
                            UserName = User.Identity.Name,
                            Vote = thisVote,
                            VoteForId = autoId
                        };
                       
                        db.VoteModels.Add(vm);
                       
                        db.SaveChanges();

                        // keep the school voting flag to stop voting by this member
                        HttpCookie cookie = new HttpCookie(url, "true");
                        Response.Cookies.Add(cookie);
                    }
                    break;
                default:
                    break;
            }
            return Json("<br />You rated " + r + " star(s), thanks !");
        }

Step 3

Now, it's time to display current rating. Create _VoteShow.cshtml partial view in the Views/Shared folder and copy-paste below code.

@model string

@{
    Single m_Average = 0;

    Single m_totalNumberOfVotes = 0;
    Single m_totalVoteCount = 0;
    Single m_currentVotesCount = 0;
    Single m_inPercent = 0;
    var thisVote = string.Empty;
   
    if (Model.Length > 0)
    {
        // calculate total votes now
        string[] votes = Model.Split(',');
        for (int i = 0; i < votes.Length; i++)
        {
            m_currentVotesCount = int.Parse(votes[i]);
            m_totalNumberOfVotes = m_totalNumberOfVotes + m_currentVotesCount;
            m_totalVoteCount = m_totalVoteCount + (m_currentVotesCount * (i + 1));
        }

        m_Average = m_totalVoteCount / m_totalNumberOfVotes;
        m_inPercent = (m_Average * 100) / 5;

        thisVote = "<span style=\"display: block; width: 65px; height: 13px; background: url(/images/starRating.png) 0 0;\">" +
            "<span style=\"display: block; width: "+ m_inPercent + "%; height: 13px; background: url(/images/starRating.png) 0 -13px;\"></span> " +
            "</span>" +
            "<span class=\"smallText\">Overall ratings: <span itemprop=\"ratingCount\">" + m_totalNumberOfVotes + "</span> | Rating: <span itemprop=\"ratingValue\">" + m_Average.ToString("##.##") + "</span> out of 5 </span>  ";
    }
}
 <div itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">
    <meta itemprop="bestRating" content="5" />
    <meta itemprop="worstRating" content="1">
    <meta itemprop="ratingValue" content="@m_Average.ToString("##.##") %>" />
      @Html.Raw(thisVote)
  </div>

Step 4

Calling rating controls (partial vies) on the post page.

<div class="tr" style="background-color:#f1f1f1;">
                <div class="td0">Please rate this school</div>
                <div class="td">@Html.Partial("_VoteNow", Model.AutoId.ToString())</div>
                <div class="td">@Html.Partial("_VoteShow", Model.Votes)</div>
            </div>


While calling _VoteNow, we are passing the unique post id as parameter and while calling _VoteShow, we are passing current votes (Rates) in the form of  "x,x,x,x,x" as parameter and here is the final output displays on the web page.

Done! Your own rating system is up and live!

Free ASP.NET MVC Hosting
Try our Free ASP.NET MVC Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



Free ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Create Cache Profiles in ASP.NET MVC

clock May 25, 2015 06:02 by author Rebecca

In this tutorial, I will tell you about creating Cache Profiles. To cache the data returned by Index() action method for 60 seconds, we would use [OutputCache] attribute as shown below:

[OutputCache(Duration=60)]
public ActionResult Index()
{
    return View(db.Employees.ToList());
}

In the example above, the OutputCache settings are specified in code. The disadvantage of this approcah is that:
1. If you have to apply the same cache settings, to several methods, then the code needs to be duplicated.
2. Later, if we have to change these cache settings, then we need to change them at several places. Maintaining the code becomes complicated. Also, changing the application code requires build and re-deployment.

To overcome these disadvantages, cache settings can be specified in web.config file using cache profiles:

Step 1

Specify cache settings in web.config using cache profiles:
<system.web>
  <caching>
    <outputCacheSettings>
      <outputCacheProfiles>
        <clear/>
        <add name="1MinuteCache" duration="60" varyByParam="none"/>           
      </outputCacheProfiles>
    </outputCacheSettings>
  </caching>
</system.web>


Step 2

Reference the cache profile in application code:
[OutputCache(CacheProfile = "1MinuteCache")]
public ActionResult Index()
{
    return View(db.Employees.ToList());
}


The cache settings are now read from one central location i.e from the web.config file. The advantage of using cache profiles is that:
1. You have one place to change the cache settings. Mantainability is much easier.
2. Since the changes are done in web.config, we need not build and redeploy the application.

Using Cache profiles with child action methods:
[ChildActionOnly]
[OutputCache(CacheProfile = "1MinuteCache")]
public string GetEmployeeCount()
{
    return "Employee Count = " + db.Employees.Count().ToString()
        + "@ " + DateTime.Now.ToString();
}


When Cache profiles are used with child action methods, you will get an error:

- Duration must be a positive number.

There colud be several ways to make cache profiles work with child action methods. The following is the approach, that I am aware of. Please feel free to leave a comment, if you know of a better way of doing this.

How to create a custom OutputCache attribute that loads the cache settings from the cache profile in web.config:

Step 1

Right click on the project name in solution explorer, and add a folder with name = Common

Step 2

Right click on "Common" folder and add a class file, with name = PartialCacheAttribute.cs

Step 3

Copy and paste the following code. Notice that, I have named the custom OutputCache attribute as PartialCacheAttribute:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Configuration;

namespace MVCDemo.Common
{
    public class PartialCacheAttribute : OutputCacheAttribute
    {
        public PartialCacheAttribute(string cacheProfileName)
        {
            OutputCacheSettingsSection cacheSettings =                 (OutputCacheSettingsSection)WebConfigurationManager.GetSection("system.web/caching/outputCacheSettings");
            OutputCacheProfile cacheProfile = cacheSettings.OutputCacheProfiles[cacheProfileName];
            Duration = cacheProfile.Duration;
            VaryByParam = cacheProfile.VaryByParam;
            VaryByCustom = cacheProfile.VaryByCustom;
        }
    }
}

Step 4

Use PartialCacheAttribute on the child action method, and pass it the name of the cache profile in web.config. Please note that, PartialCacheAttribute is in MVCDemo.Common namespace.
[ChildActionOnly]
[PartialCache("1MinuteCache")]
public string GetEmployeeCount()
{
    return "Employee Count = " + db.Employees.Count().ToString()
        + "@ " + DateTime.Now.ToString();
}

Free ASP.NET MVC Hosting
Try our Free ASP.NET MVC Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



Free ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Use Entity Framework to Insert, Update and Delete Data in ASP.NET MVC

clock May 22, 2015 07:01 by author Rebecca

In this tutorial, I will tell you about selecting, inserting, updating and deleting data in mvc using entity framework. I will be using tables tblDepartment and tblEmployee for this tutorial.

Step 1

First you must run the sql script to create and populate these tables, here is the example:

Create table tblDepartment
(
 Id int primary key identity,
 Name nvarchar(50)
)

Insert into tblDepartment values('IT')
Insert into tblDepartment values('HR')
Insert into tblDepartment values('Payroll')

Create table tblEmployee
(
 EmployeeId int Primary Key Identity(1,1),
 Name nvarchar(50),
 Gender nvarchar(10),
 City nvarchar(50),
 DepartmentId int
)

Alter table tblEmployee
add foreign key (DepartmentId)
references tblDepartment(Id)

Insert into tblEmployee values('Mark','Male','London',1)
Insert into tblEmployee values('John','Male','Chennai',3)
Insert into tblEmployee values('Mary','Female','New York',3)
Insert into tblEmployee values('Mike','Male','Sydeny',2)
Insert into tblEmployee values('Scott','Male','London',1)
Insert into tblEmployee values('Pam','Female','Falls Church',2)
Insert into tblEmployee values('Todd','Male','Sydney',1)
Insert into tblEmployee values('Ben','Male','New Delhi',2)
Insert into tblEmployee values('Sara','Female','London',1)

Step 2

Create a new asp.net mvc 4 web application. Then Right click on the "Models" folder and add "ADO.NET Entity Data Model". Set Name = EmployeeDataModel.edmx.

On the subsequent screen, select "Generate from database" option and click "Next". On "Choose your data connection screen", click on "New Connection" button. Specify the sql server name. In my case, I have sql server installed on my local machine. So I have set "Server Name=(local)". From "Select or enter a database name" dropdownlist, select the Database name and click "OK". Then Click "Next".

Step 3

On "Choose your database objects" screen, expand "Tables" and select "tblDepartment" and "tblEmployee" tables. Set "Model Namespace=Models" and click "Finish".

At this point we should have tblDepartment and tblEmployee entities generated.
a) Change tblDepartment to Department
b) Change tblEmployee to Employee
c) Change tblEmployees nvigation property to Employees
d) Change tblDepartment nvigation property to Department

Step 4

Right click on the "Controllers" folder and select Add - Controller. Then, Set:
Name = EmployeeController
Template = MVC controller with read/write actions and views, using Entity Framework
Model class = Employee(MVCDemo.Models)
Data Context Class = EmployeeContext(MVCDemo.Models)
Views = Razor

Finally click "Add".

At this point you should have the following files automatically added.
1. EmployeeController.cs file in "Controllers" folder
2. Index, Create, Edit, Detail and Delete views in "Employee" folder.

On Create and Edit views, please delete the following scripts section. We will discuss these in a later video session.
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


At this point, if you run the application by pressing CTRL + F5, you will get an error stating - The resource cannot be found. This is because, by default, the application goes to "HOME" controller and "Index" action.

To fix this,
1. Open "RouteConfig.cs" file from "App_Start" folder
2. Set Controller = "Employee"

Run the application again. Notice that, all the employees are listed on the index view. We can also create a new employee, edit an employee, view their full details and delete an employee as well.

Free ASP.NET MVC Hosting
Try our Free ASP.NET MVC Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



About HostForLIFE.eu

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 offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in