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

Free ASP.NET MVC 5 Hosting - HostForLIFE.eu :: How to Create Web Application with ASP.NET MVC 5

clock June 5, 2015 06:04 by author Rebecca

This post will show you how to create a new ASP.NET MVC 5 application using Visual Studio 2013.

Step 1

Open Visual Studio 2013. It goes without saying, you're gonna need Visual Studio to create a web application using ASP.NET, and the version you will need for ASP.NET MVC 5 is Visual Studio 2013.

Step 2

Create a new ASP.NET MVC 5 Application:

  • Click File, New, then Project.

  • Select Web, then ASP.NET Web Application, give the project a name, and then click OK.

  • Select the MVC template, tick Add unit tests, and then click OK.

Step 3

Update existing NuGet packages. Click on Tools, then NuGet Package Manager, then NuGet Package Manager Console.

Then, enter the following command into the Package Manager Console window:

Update-Package

This will update all the existing packages.

Step 4

Run your new web application for the first time. Click on the MyWebApplication project, and then click the Play icon to launch the website.

Step 5

Admire your new project!

That's it!

A newly created web application that includes some impressive functionality out of the box. The default template gives you:

  • Bundling and minification.
  • The ability to register, and sign into your account.
  • A snazzy prebuilt layout that uses bootstrap.
  • And you get a framework that lets you create scaleable web applications using the well-established MVC design pattern.

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 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.



ASP.NET MVC 6 Hosting - HostForLife.eu :: How to Produce Ouput in ASP.NET using Different Action Method (Content (), Json(), File () Action Method)

clock May 15, 2015 06:27 by author Rebecca

Are you still remember about the article that has told you about how to produce output to the web page using JavaScript Action Method in ASP.NET MVC. To continue the article, today I'm gonna tell you how to produce output to the web page from controller using the last 3 action methods: Content (), Json (), File () Action Method).

Content() Action Method

Content() method renders the string that is passed as parameter to the browser.

public ContentResult OutputContent()
        {
            return Content("This is content.");
        }

When above controller method is called, it simply render "This is content." in the browser. This method returns ContentResult action result that derives from ActionResult.

Json() Action Method

Json() method returns Json string to the browser. Its return type is JsonResult that derives from ActionResult.

public JsonResult OutputToJson()
        {
            UserNamePasswordModel model = new UserNamePasswordModel()
            {
                Password = "Password1",
                UserName = "UserName1"
            };
            return Json(model, JsonRequestBehavior.AllowGet);
        }

// OUTPUT: {"UserName":"UserName1","Password":"Password1"}

The above code converts the UserNamePasswordModel to the Json string and returns to the browser.

File() Action Method

File() action method returns the content of a file to the browser. The return type of this method is FileResult that again derives from ActionResult.

public FileResult OutputFile()
        {
            string path = Server.MapPath("~/Views/Home/About.cshtml");
            return File(path, "text/html");
        }


Hope this article was helpful. Thanks for reading and keep visiting for more ASP.NET MVC related articles.

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 Produce Output in ASP.NET MVC using Different Action Methods (JavaScript Action Method)

clock May 8, 2015 05:56 by author Rebecca

Continuing the article that has told you about how to produce output to the web page using Redirect Action Method in ASP.NET MVC. Today, I will show you how to produce output to the web page from controller using JavaScript Action Method.

JavaScript() action method returns JavaScript code to the browser. This method returns JavaScriptResult action result that derives from ActionResult class.

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

To test this, create a view with following code:

Try clicking on the link below
 
@Ajax.ActionLink("Test JavaScript", "OutputJavaScriptAlert", new AjaxOptions{UpdateTargetId = "divLink"})


Now, after running your project try clicking on the link and you will get an alert like below.

Simple, right? That's the way to produce output in ASP.NET MVC using Redirect Action Method. Just look forward to further discussion in the next article.

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 Produce Output in ASP.NET MVC using Different Action Methods (Redirect Action Method)

clock May 4, 2015 06:13 by author Rebecca

Continuing the article that has told you about how to produce output to the web page using View Action Method in ASP.NET MVC. Today, I will show you how to produce output to the web page from controller using Redirect Action Method.

Redirect ("url") Action Method

Redirect() action method when passed url as parameter redirect user to the url that is passed.

 public RedirectResult OutputRedirectView()
        {
            return Redirect("/controllerandaction/ReceiveWithRequestFormCollection");
        }

The above code will redirect user to "ReceiveWithRequestFormCollection" method of "controllerandaction" controller. Redirect() method returns RedirectResult action result that derives from ActionResult.

RedirectToRoute() Action Method

RedirectToRoute() action method when passed Route name as parameter redirects the user to that particular route defined in App_Start/RouteConfig.cs. This method returns RedirectToRouteResult action result that intern derive from ActionResult class.

public RedirectToRouteResult OutputToAction()
        {
            // return RedirectToAction("OutputPartialView");
            return RedirectToRoute("MyCustomRoute");
        }

Route Config

 routes.MapRoute(
                name: "MyCustomRoute",
                url: "CustomController/{action}/{id}",
                defaults: new { action = "Index", id = UrlParameter.Optional }
            );


The parameters, if any defined in the route gets its default value, if not we need to pass 2nd parameter as route values.

return RedirectToRoute("MyCustomRoute", new { Id = 5 });

PartialView("_PartialViewName") action method

PartialView() action method when passed partial view name as parameter returns the Partial View as a web page.

public PartialViewResult OutputPartialView()
        {
            return PartialView("_MyPartialView");
        }


This method can accept 2nd parameter as model object to return along with the partial view so that this view can use Model to retrieve data. PartialView() method returns PartialViewResult action result that intern derives from ActionResult class.

That's the way to produce output in ASP.NET MVC using Redirect Action Method. Just look forward to further discussion in the next article.

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 s
egments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Produce Output in ASP.NET MVC using Different Action Methods (View Action Method)

clock April 24, 2015 06:40 by author Rebecca

Action methods are the obvious way to produce output to the web page from controller in ASP.NET MVC. It can be a complete web page, a string or an object. Start from today until the next few days, we're going to learn different ways to produce output to the web page using action methods in ASP.NET MVC. Each action method returns different types of action results, however, most of action results derives from "ActionResult" class so returning "ActionResult" from these controller method would suffice your need.

In this part, I will show you how to use View Action Methods that are available to produce an output in ASP.NET MVC.

View() Action Method

View() action method is used to render a view as a web page. In this case, View will be the .cshtml page available in the View folder with the name of the method from which this is being called.

    public ViewResult OutputView()
            {
                return View();
            }


The above View() method will render OutputView.cshtml (the location of this View depends on under which controller this method is written) from Views folder to the browser. View() method returns ViewResult action type that derives from ActionResult class.

View(Model) Action Method

View() method when passed with an object as a parameter returns the View as a web page, with the object (model) being passed so that View can use this model to render data.

    public ViewResult OutputViewWithModel(UserNamePasswordModel model)

            {
  return View(model); // returns view with model

            }    The above method will render OutputViewWithModel.cshtml from Views folder to the browser.
The View must have @model directive in order to retrieve data from Model.

    @model Restaurant.Models.UserNamePasswordModel

    @{

        ViewBag.Title = Model.UserName;
     }

View("ViewName") Action method

View() method when passed with the View name renders the view that is passed as parameter as a web page.

    public ViewResult OutputViewWithModel(UserNamePasswordModel model)
            {
                return View("OutputView"); // returns the view that is passed as paramter
            }

The above code will render "OutputView" view to the page. Please note that View name should not contain the extension name (.cshtml) of the view.

That's the way to produce output in ASP.NET MVC using View Action Method. Just look forward to further discussion in the next article.

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 Hosting - HostForLIFE.eu :: Creating a Custom Remote Attribute and Override IsValid() Method

clock April 20, 2015 06:12 by author Rebecca

Today, I'm gonna tell you how to create a costum remote attribute and override IsValid() Method. In addition, remote attribute only works when JavaScript is enabled. If you disables JavaScript on your machine then the validation does not work. This is because RemoteAttribute requires JavaScript to make an asynchronous AJAX call to the server side validation method. As a result, you will be able to submit the form, bypassing the validation in place. This why it is always important to have server side validation.

To make server side validation work, when JavaScript is disabled, there are 2 ways:

  1. Add model validation error dynamically in the controller action method.
  2. Create a custom remote attribute and override IsValid() method.

How to Create a Costum Remote Attribute

Step 1:

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

Step 2:

Right click on the "Common" folder, you have just added and add a class file with name = RemoteClientServer.cs

Step 3:

Copy and paste the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.Reflection;

namespace MVCDemo.Common
{
    public class RemoteClientServerAttribute : RemoteAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            // Get the controller using reflection
            Type controller = Assembly.GetExecutingAssembly().GetTypes()
                .FirstOrDefault(type => type.Name.ToLower() == string.Format("{0}Controller",
                    this.RouteData["controller"].ToString()).ToLower());
            if (controller != null)
            {
                // Get the action method that has validation logic
                MethodInfo action = controller.GetMethods()
                    .FirstOrDefault(method => method.Name.ToLower() ==
                        this.RouteData["action"].ToString().ToLower());
                if (action != null)
                {
                    // Create an instance of the controller class
                    object instance = Activator.CreateInstance(controller);
                    // Invoke the action method that has validation logic
                    object response = action.Invoke(instance, new object[] { value });
                    if (response is JsonResult)
                    {
                        object jsonData = ((JsonResult)response).Data;
                        if (jsonData is bool)
                        {
                            return (bool)jsonData ? ValidationResult.Success :
                                new ValidationResult(this.ErrorMessage);
                        }
                    }
                }
            }

            return ValidationResult.Success;
            // If you want the validation to fail, create an instance of ValidationResult
            // return new ValidationResult(base.ErrorMessageString);
        }

        public RemoteClientServerAttribute(string routeName)
            : base(routeName)
        {
        }

        public RemoteClientServerAttribute(string action, string controller)
            : base(action, controller)
        {
        }

        public RemoteClientServerAttribute(string action, string controller,
            string areaName) : base(action, controller, areaName)
        {
        }
    }
}

Step 4:

Open "User.cs" file, that is present in "Models" folder. Decorate "UserName" property with RemoteClientServerAttribute.

RemoteClientServerAttribute is in MVCDemo.Common namespace, so please make sure you have a using statement for this namespace.
public class UserMetadata
{
    [RemoteClientServer("IsUserNameAvailable", "Home",
        ErrorMessage="UserName already in use")]
    public string UserName { get; set; }
}

Disable JavaScript in the browser, and test your application. Notice that, we don't get client side validation, but when you submit the form, server side validation still prevents the user from submitting the form, if there are validation errors.

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. You will not be charged a cent for trying our service for the next 3 days. Once your trial period is complete, you decide whether you'd like to continue.



Free ASP.NET MVC Hosting - HostForLIFE.eu :: Processing Form Data using MVC Pattern

clock April 17, 2015 05:57 by author Rebecca

In this post, I will show you how to send form data to controller class using MVC pattern. Here, we will create simple HTML form and will send data to controller class, and then we will display same data in another view.

Step 1: Create Model Class

At first, we will create one simple model class called “Person” for this example.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MVC3.Models
{
    public class Person
    {
        public String Name{ get; set; }
        public StringSurname { get; set;
    }
    }
}

Step 2: Create simple HTML Form to Take Input

It’s view in MVC architecture. We will create two textboxes and one submit button in this view.
<%@ Page
Language="C#"
Inherits="System.Web.Mvc.ViewPage<dynamic>"
%>
<!DOCTYPE html>
<html>
<head runat="server">
    <title>PersonView</title>
</head>
<body>
    <div>
    <form method="post" action="Person/SetPerson">
        Enter Name:- <input type="text" id="Name" name="Name" /> <br />
        Entersurname:- <input type="text" id="surname" name="surname" />
        <input type="submit" value="Submit" />
    </form>
    </div>
</body>
</html>

Step 3: Create simple Controller to Invoke the View.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC3.Models;
namespace MVC3.Controllers
{
    public class PersonController : Controller
    {
        //
        // GET: /Person/
        public ActionResult ShowForm()
        {
            return View("PersonView");
        }
        [HttpPost]
        public ActionResult SetPerson()
        {
            String Name = Convert.ToString(Request["Name"]);
            String Surname = Convert.ToString(Request["surname"]);
            Person p = new Person();
            p.Name = Name;
            p.Surname = Surname;
            ViewData["Person"] = p;
            return View("ShowPerson");
        }
 
    }
}

In this controller, we are seeing two actions the ShowForm() action is the default action for Person Controller and SetPerson() action will call another view to display data. We can see within SetPerson() action,we are creating object of controller class and assigning value to it. At last we are assigning populated object to ViewData. Then we are calling one view called “ShowPerson”. This view will display data.

Create showPerson view

<%@ Page
Language="C#"
Inherits="System.Web.Mvc.ViewPage<dynamic>"
%>
<!DOCTYPE html>
<html>
<head runat="server">
    <title>ShowPerson</title>
</head>
<body>
    <div>
    <% var P = (MVC3.Models.Person)ViewData["Person"];%>      
       Person Name is :- <%= P.Name %> <br />      
       Person Surname is :- <%= P.Surname %>
    </div>
</body>
</html>

Here is the sample output:

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. You will not be charged a cent for trying our service for the next 3 days. Once your trial period is complete, you decide whether you'd like to continue.



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