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 Hosting - HostForLIFE.eu :: Action Method In ASP.NET MVC

clock December 20, 2024 08:02 by author Peter

ASP.NET MVC action methods are responsible to execute the request and generate a response to it. All the public methods of the MVC Controller are action methods. If we want the public method to be a  non-action method, then we can decorate the action method by “NonAction” attribute. It will restrict the action method to render on the browser.

 
To work with action method we need to remember the following points.

  • The action method is the public non-static method.
  • Action method can not be the private or protected method.
  • Action method can not contain ref and out parameters.
  • Action method can not be an extension method.
  • Action method can not be overloaded.

Example of an action method in ASP.NET MVC 5 is as below.

    public class HomeController : Controller  
        {  
            // GET: Home  
            public ActionResult Index()  
            {  
                return View();  
            }  
    }  


You can see in the above action method example that the Index() method is a public method which is inside the HomeController class. And the return type of the action method is ActionResult. It can return using the “View()” method. So, every public method inside the Controller is an action method in MVC.
 
Action Method can not be a private or protected method.
    public class HomeController : Controller  
        {  
            // GET: Home  
            private ActionResult Index()  
            {  
                return "This is Index Method";          
            }  
    }  


If you provide the private or protected access modifier to the action method, it will provide the error to the user, i.e., “resource can not be found” as below.

Action method can not be overloaded.
    public string Index()  
           {            
               return "This is Index Method";  
           }  
      
           public string Index(int id)  
           {  
               return "This is Index overloaded Method";  
           }  

If you try to overload the action method, then it will throw an ambiguous error.

An action method cannot contain ref and out parameters.
    public string Index(ref int id)  
            {  
                return "This is Index Method" +id;  
            }  

    public string Index(out int id)  
           {  
               id = 0;  
               return "This is Index Method" +id;  
           }  


We can not provide the ref and out parameters to the action method. If you try to provide the ref and out parameters to the action method, then it will throw an error as below.



Action method can not be overloaded.
    public string Index()  
           {            
               return "This is Index Method";  
           }  
      
           public string Index(int id)  
           {  
               return "This is Index overloaded Method";  
           }  


If you try to overload the action method, then it will throw an ambiguous error.


 
Types of Action Method.

  • Action Method
  • Non Action Method

How to restrict the public action method in MVC?
To restrict the public action method in MVC, we can use the “NonAction” attribute. The “NonAction” attribute exists in the “System.Web.MVC” namespace.
 
Example of NonAction attribute in ASP.NET MVC.
    [NonAction]  
      public string GetFullName(string strFirstName, string strLastName)  
      {  
              return strFirstName + " " + strLastName;  
      }  

How to call Action Method?
Syntax

YourDomainName/ControllerName/ActionMethodName
 
Example
 
localhost/Home/Index

How to change default Action Method?
The default Action method is configured in the RouteConfig.cs class. By default, the Action Method is the “Index” action method. Change the “Index” action method name as per our requirement.
    public static void RegisterRoutes(RouteCollection routes)  
            {  
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
      
                routes.MapRoute(  
                    name: "Default",  
                    url: "{controller}/{action}/{id}",  
                    defaults: new { controller = "Home", action = "Message", id = UrlParameter.Optional }  
                );  
            }  

You can see in the above code that we have changed the action method name to “Message” instead of “Index” by default.
 
How does the default action get executed?
Default controller and action method are configured in RouteConfig.cs class. By default, Controller is the Home Controller and default Action Method is the “Index” action method.
 
Example of default action method
    public static void RegisterRoutes(RouteCollection routes)  
            {  
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
      
                routes.MapRoute(  
                    name: "Default",  
                    url: "{controller}/{action}/{id}",  
                    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }  
                );  
            }  



ASP.NET MVC Hosting - HostForLIFE.eu :: Session in ASP.NET Core MVC .NET 8

clock December 11, 2024 06:09 by author Peter

What is a Session?
Session is KEY-VALUE structure to store the user specific data. In Asp.Net Core .NET 8 session is not enable by default, we have to enable it. Session data persists across multiple HTTP requests.


How many ways for Session storage?

In-Memory Cache: Server base storage. Storage capacity is depend upon server’s available memory. Best for single server base environment.
Distributed Cache: Session storage not on one server its store on multiple server. Distributed cache work with Redis, Sql Server etc. .

How to Enable Session in .Net 8 Asp.Net Core MVC Application?

builder.Services.AddSession();

Add another line just after app declaration line:
app.UseSession();

How to set or store the value in session?
Create or Setting Session value.

Syntax
HttpContext.Session.SetString(KEY,VALUE);
HttpContext.Session.SetInt22(KEY,VALUE);


Example
HttpContext.Session.SetString(“USERNAME”, UserName);
HttpContext.Session.SetString(“USERID”,Convert.ToString(UserID));

How to get or retrieve the value of session?
Getting Session value.

Syntax
HttpContext.Session.GetString(KEY);

HttpContext.Session.GetInt22(KEY);


Example
HttpContext.Session.GetString(“USERNAME”);

HttpContext.Session.GetString(“USERID”);


How to remove particular session key?
You can easily remove a specific session key.

Syntax
HttpContext.Session.Remove(KEY);

Example
HttpContext.Session.Remove(“UESERNAME”);

How to remove all session keys?
You can delete/remove/clear all sessions in one go.

HttpContext.Session.Clear();


Clear: It remove all the current session entries from the server.

OR

HttpContext.SignOutAsync();

SignOutAsync: It end the current user session and remove or clear the user’s authentication cookie from the server.
Walk-through on session implementation

In this article I had used Visual Studio 2022. After follow step by step you are able to implement SESSION in your Asp.Net Core project.

 

 

Above screenshot is a view of default project structure of Asp.Net Core .NET 8.

Now open program.cs file to add following line:
builder.Services.AddSession(); //

app.UseSession(); //after app declaration.


Update Program.cs file Code:
var builder = WebApplication.CreateBuilder(args);

// Add services to the container
builder.Services.AddControllersWithViews();

// Configure session service for the application
builder.Services.AddSession();

var app = builder.Build();

// Enable the Session Middleware
app.UseSession();

// Configure the HTTP request pipeline
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Open the HomeController.cs file from CONTROLLERS folder.

Update HomeController.cs file code:
using LearnCore.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

namespace LearnCore.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            // Create SESSION called USERNAME and store value "Peter Scott"
            HttpContext.Session.SetString("USERNAME", "
Peter Scott");
            return View();
        }

        public IActionResult Privacy()
        {
            // Get value from SESSION
            string UserValName = HttpContext.Session.GetString("USERNAME")?.ToString();
            ViewBag.UserName = UserValName;
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

Open the Privacy.cshtml file from VIEWS àHOME.

Update the Privacy.cshtml file code :
@{
    ViewData["Title"] = "Privacy Policy";
}

<h1>@ViewData["Title"]</h1>

<p>Use this page to detail your site's privacy policy.</p>

<h2>
    User Name: <i><u>@ViewBag.UserName</u></i>
</h2>

Now press F5 to run the project. Happy Coding!



ASP.NET MVC Hosting - HostForLIFE.eu :: Application Using Backbone.js with ASP.NET MVC

clock December 3, 2024 07:37 by author Peter

This article shows the use of Backbone.js with ASP.NET MVC with a simple MVC application using backbone.js. Before this article we used backbone with HTML but here we will use with cshtml.



Use the following procedure to create the sample.

Step 1

  • Create a Web API application with the following:
  • Start Visual Studio 2013.
  • From Start window Select "New Project".
  • Select "Installed" -> "Template" -> "Visual C#" -> "Web" -> "Visual Studio 2012" and select "ASP.NET MVC4 Web Application".
  • Click the "OK" button.

From the MVC4 project window select "Empty application".

Click on the "OK" button.

Step 2
Now add a MVC controller class in the Controller folder.

  • In the Solution Explorer.
  • Right-click on the Controller folder.
  • Select "Add" -> "Controller" then select "Empty MVC Controller" and click on the "Add" button.

Add the "Person Action method".
public class HomeController : Controller
{
    //
    // GET: /Home/
    public ActionResult Index()
    {
        return View();
    }
    public ActionResult Person()
    {
        return View();
    }
}


Now we need to add a "index.cshtml" view in the Home folder. Right-click on the "Person()" action method, select "Add view" then open an "Add View" window then click on the "Add" button.

Add the following code in this view:
@{
    ViewBag.Title = "Person";
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Backbone.js Web App</title>
    <link href="~/Content/style.css" rel="stylesheet" type="text/css"/>
</head>
<body>
    <div id="persons"></div>
    <script id="personTemplate" type="text/template">
        <img src="<%= photo %>" alt="<%= name %>" />
        <h1><%= name %><span><%= type %></span></h1>
        <div><%= address %></div>
        <dl>
            <dt>Tel:</dt>
            <dd><%= tel %></dd>
            <dt>Email:</dt>
            <dd><a href="mailto:<%= email %>"><%= email %></a></dd>
        </dl>
    </script>
    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script src="~/Scripts/json2.js"></script>
    <script src="~/Scripts/underscore-min.js"></script>
    <script src="~/Scripts/backbone-min.js"></script>
    <script src="~/Scripts/main.js" type="text/javascript"></script>
    </div>
</body>
</html>

Step 3
Now we create a JavaScript file as "main.js".

  • In the Solution Explorer.
  • Right-click on the "Scripts" folder select "Add" -> "JavaScript".

Click on the "Add" button.

Add the following code;
(function ($) {
    //demo data
    var persons = [       { name: "Person 1", address: "Address 1", tel: "0123456789", email: "[email protected]", type: "family" },       { name: "Person 2", address: "Address 2", tel: "0123456789", email: "[email protected]", type: "family" },
    ];
    //define product model
    var Person= Backbone.Model.extend({
        defaults: {
            photo: "img/placeholder.png"
    }
    });
//define directory collection
var Directory = Backbone.Collection.extend({
    model: Person
});
//define individual person view
var PersonView = Backbone.View.extend({
    tagName: "article",
    className: "person-container",
    template: $("#personTemplate").html(),
    render: function () {
        var tmpl = _.template(this.template);
        $(this.el).html(tmpl(this.model.toJSON()));
        return  this;
    }
});
//define master view
var DirectoryView = Backbone.View.extend({
    el: $("#persons"),
    initialize: function () {
        this.collection = new Directory(persons);
        this.render();
    },
    render: function () {
        var that = this;
        _.each(this.collection.models, function (item) {
            that.renderPerson(item);
        }, this);
    },
    renderPerson: function (item) {
        var personView = new PersonView({
            model: item
        });
        this.$el.append(personView.render().el);
    }
});
//create instance of master view
var directory = new DirectoryView();
} (jQuery));

There is were we need the other scripting files "backbone.js","underscore.js", "json2.js" and "jquery-1.8.2.min.js".

Step 4
Now execute the application:



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