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 :: Knowing EF Core MVC's Connected Disconnected Scenarios

clock January 7, 2025 06:56 by author Peter

Working with data is essential in contemporary online applications, and Entity Framework Core (EF Core) offers a productive method of interacting with databases through the use of Object-Relational Mapping (ORM). The Connected and Disconnected scenarios are the two main methods that EF Core provides for handling data in an application. Both situations differ in how data is recorded, accessed, and stored in the database, and they are crucial in distinct use cases. Both of these ideas are examined in this article along with workable solutions in a.NET Core MVC application.

What is a Connected Scenario?
In a Connected scenario, the DbContext is directly connected to the entity instances and actively tracks changes made to the data. This is the default behavior of EF Core when entities are retrieved using a context and modified within the scope of the context.

  • Key Characteristics of a Connected Scenario
  • Change Tracking: EF Core automatically tracks changes made to the entities. When SaveChanges() is called, it updates the database with those changes.
  • Short-lived Context: The DbContext instance is created, used, and disposed of within a limited scope, often tied to a single HTTP request in a web application.
  • Automatic State Management: EF Core keeps track of the state of entities, such as Added, Modified, Deleted, and Unchanged.

Practical Example
Let’s create a simple CRUD operation in a Connected scenario for managing a list of users.

Create the Model
namespace EFCoreConnectedDisconnectedDemo.Model
{
    public class User
    {
        public int Id { get; set; }
        public string? Name { get; set; }
        public string? Email { get; set; }
    }
}

Set Up DbContext
using EFCoreConnectedDisconnectedDemo.Model;
using Microsoft.EntityFrameworkCore;

namespace EFCoreConnectedDisconnectedDemo.ApplicationContext
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }

        public DbSet<User> Users { get; set; }
    }
}

Create the controller

using EFCoreConnectedDisconnectedDemo.ApplicationContext;
using EFCoreConnectedDisconnectedDemo.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace EFCoreConnectedDisconnectedDemo.Controllers
{
    public class UserController : Controller
    {
        private readonly ApplicationDbContext _context;

        public UserController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: User
        public IActionResult Index()
        {
            var users = _context.Users.ToList();
            return View(users);
        }

        // GET: User/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: User/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create([Bind("Id, Name, Email")] User user)
        {
            if (ModelState.IsValid)
            {
                _context.Add(user);
                _context.SaveChanges(); // Save the changes in the connected scenario
                return RedirectToAction(nameof(Index));
            }
            return View(user);
        }

        // GET: User/Edit/5
        public IActionResult Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var user = _context.Users.Find(id);
            if (user == null)
            {
                return NotFound();
            }
            return View(user);
        }

        // POST: User/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Edit(int id, [Bind("Id, Name, Email")] User user)
        {
            if (id != user.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(user);
                    _context.SaveChanges(); // EF Core automatically tracks changes and updates the database
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!_context.Users.Any(e => e.Id == user.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(user);
        }

        // GET: User/Delete/5
        public IActionResult Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var user = _context.Users
                .FirstOrDefault(m => m.Id == id);
            if (user == null)
            {
                return NotFound();
            }

            return View(user);
        }

        // POST: User/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public IActionResult DeleteConfirmed(int id)
        {
            var user = _context.Users.Find(id);
            _context.Users.Remove(user);
            _context.SaveChanges(); // EF Core will automatically track the deletion
            return RedirectToAction(nameof(Index));
        }
    }
}


Create the Views
Index.cshtml, Create.cshtml, Edit.cshtml, and Delete.cshtml are Razor views for handling the respective CRUD actions.

How it Works in a Connected Scenario?

  • Tracking Changes: EF Core tracks changes made to User entities in the database automatically.
  • Saving Changes: Calling SaveChanges() saves the changes (whether added, updated, or deleted) to the database.

What is a Disconnected Scenario?
In a Disconnected scenario, the DbContext is not available to track changes once the data is retrieved from the database. This scenario is common in applications where the DbContext is disposed of after the entity data is fetched, such as in web APIs where entities are transferred over HTTP.

Key Characteristics of a Disconnected Scenario

  • No Change Tracking: Entities are not tracked once the DbContext is disposed of, meaning changes must be manually managed.
  • Manual State Management: In disconnected scenarios, the entity must be explicitly attached to the context and marked with its state (e.g., Modified) when changes are saved.
  • Common in Web APIs: Commonly used in Web API scenarios where entities are transferred to and from clients and must be handled after detaching from the context.

Practical Example
Let’s handle a simple scenario where data is fetched in a disconnected manner, then updated and saved.

Create a Web API Controller for Disconnected Scenario
using EFCoreConnectedDisconnectedDemo.ApplicationContext;
using EFCoreConnectedDisconnectedDemo.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace EFCoreConnectedDisconnectedDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ApiUserController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public ApiUserController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: api/ApiUser/5
        [HttpGet("{id}")]
        public ActionResult<User> GetUser(int id)
        {
            var user = _context.Users.Find(id);
            if (user == null)
            {
                return NotFound();
            }
            return user;
        }

        // PUT: api/ApiUser/5
        [HttpPut("{id}")]
        public IActionResult PutUser(int id, User user)
        {
            if (id != user.Id)
            {
                return BadRequest();
            }

            // In disconnected scenario, we must attach the entity back to the context and mark it as modified
            _context.Users.Attach(user);
            _context.Entry(user).State = Microsoft.EntityFrameworkCore.EntityState.Modified;

            try
            {
                _context.SaveChanges(); // Save changes to the database manually
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!_context.Users.Any(e => e.Id == user.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }
    }
}


How it Works in a Disconnected Scenario?
The data is fetched and passed to the client (e.g., as JSON).

When the client sends an updated version of the entity, the entity must be explicitly attached to the DbContext.

The entity is marked as modified, and the changes are saved by calling SaveChanges().

When to Use Each Scenario?

  • Connected Scenario: Best suited for web applications or APIs where the DbContext remains active throughout the request lifecycle. It simplifies the development process since EF Core automatically handles change tracking.
  • Disconnected Scenario: Ideal for web APIs and scenarios where the DbContext is not available after data is retrieved. It requires explicit management of entity states and is suitable for distributed systems or client-server models.

Conclusion
In this post, we looked at how to use Entity Framework Core in an ASP.NET Core MVC application to manage connected and disconnected circumstances. Knowing the distinctions between these two methods can help you decide whether your application needs manual state management (disconnected) or automatic change monitoring (connected) for data management. Both situations are necessary for developing effective and reliable data-driven applications and are crucial in various use cases.



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:



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: ASP.NET MVC With Knockout.Js

clock November 21, 2024 07:36 by author Peter

Fundamentals of MVVM
Developers will soon find the MVVM design pattern in Silverlight and WPF necessary. Martin Fowler's Presentation Model, which gathers strength from MVC and MVP flexible structures, serves as the foundation for the MVVM architecture. The UI design patterns with Code-Behind are meant to be entirely or partially distinct from one another.


 
The three primary components of MVVM are Model, View, and ViewModel. When the View is totally ignorant of the model, ViewModel makes reference to it. This eliminates the developer's need to interact with the business logic interface.


The diagram above describes the situation in the best way. The Model may vary throughout the project. The View is unaware of this situation. The Model is isolated from the View. The ViewModel is a middle man for managing the binding and commands.
 
With Only jQuery on MVC
Let's talk about jQuery. jQuery has a strong binding mechanism that uses HTML tag ids, a CSS class and a HTML tag name. Values are pushed from the source object into the HTML elements, thus requiring a line of code for each mapping from the source value to the target element. It's much easier with KO. It lets you scale up in complexity without fear of introducing inconsistencies. jQuery is simple to bind with values and tags.
 
jQuery cannot serve us in the following ways:
Any source object changes will not reflected on HTML elements. (You can push values and call again.)
Any changes in the HTML elements won't be reflected on source objects.

Code:
    <h2>Using Jquery  
        Without Knockout</h2>  
    <span>StudentNumber:</span><span id="StudentNumber"></span>  
    <br />  
    <span>Surname:</span><input id="StudentSurName" />  
    <span>Name:</span><input id="StudentName" />  
    <script type="text/javascript">  
    $(document).ready(function() {  
        var student = {  
            Number: "A123456",  
            Surname: "Leon",  
            Name: "Alexander"  
        };  
        $("#StudentNumber").text(student.Number);  
        $("#StudentSurName").val(student.Surname);  
        $("#StudentName").val(student.Name);  
    });  
    </script>  

You can bind your values to HTML tags using the HTML tag's id and CSS classes. jQuery is an excellent low-level way to manipulate elements and event handlers on a web page. jQuery doesn't have a concept of an underlying data model. If you bind the values of any object like above, you will not observe any changes in the UI after any change of the Model. You must refresh web pages to observe View changes. On the other hand; if you change the HTML element's value then your model won't be fired.

What is knockout.js?

KO is not an alternative to jQuery or other js libraries (Prototype, MooTools). KO focuses on MVVM to manipulate the Model to the View from AJAX calls. KO manages between the ViewModel and View the automatic relation that is triggered by user interface calls.
 
Model: Business Logic.
View:   HTML/CSS. If you change the ViewModel's objects, the View will be effected automatically.
ViewModel: He is a middle man to observable connection Model and View because the Model doesn't have any knowledge of the View.
 
Observable and Binding: KO's focus is on the Data-Driven js concepts; in other words, any changes in the View will fire the model; also the model's changes will automatically fire the View's updates. KO is on the alert to communicate between them in both directions.

Code:
<h2>With Knockout</h2>  
<span>Student Number:</span><span data-bind="text: Number"></span>  
<br />  
<span>Surname:</span><input data-bind="value: Surname" />  
<span>Name:</span><input data-bind="value: Name" />  
<script type="text/javascript">  
var student = {  
    Number: "A123456",  
    Surname: "Leon
",  
    Name: "Alexander"  
}  
// Activates knockout.js  
ko.applyBindings(student);  
</script>  

The HTML tag binding is unable to observe the Data-Bind structure. KO concentrates on data-binding via the data-bind tag. But the preferred usage is the following. It is useful to control the View's changes for values of the Model's objects. Observable property is one of the most important things. MVVM needs to observe any changes in UI. KO will consider any changes to the View. Actually, when you edit one of those text boxes, it does update the underlying ViewModel data.

Update your ViewModel to make the Name and Surname properties observable using ko.observable:

<script type="text/javascript">  
var student = {  
    Number: ko.observable("A123456"),  
    Surname: ko.observable("Leon"),  
    Name: ko.observable("Alexander")  
}  
// Activates knockout.js  
ko.applyBindings(student);  
</script>  


Now re-run the application and edit the text boxes. This time you'll see not only that the underlying ViewModel data is being updated when you edit, but that all associated UI is updating in sync with it too.

Simple Usage Knockout on MVC
Real-World applications need to be fed from a database. So, the Model would be your application's stored data that would be implemented using a server-side technology. The View is always interested in the UI requests. The Viewmodel contains objects to manage any responses from the View. A programmer must be able to imagine how to generate a ViewModel, not only WPF but also data-driven HTML pages. Data-driven means that the implementation of the ViewModel uses JavaScript.
 
Sometimes, we don't need to implement the ViewModel with JavaScript. We can bind the server-side Model to the View. "@Html.Raw(Json.Encode(Model));" is an effective way to bind the Server-side Model to the View.

Model: public class Student {  
        public string Number {  
            get;  
            set;  
        }  
        public string Name {  
            get;  
            set;  
        }  
        public string Surname {  
            get;  
            set;  
        }  
    }  
    //Controller:  
      
    [HttpGet]  
    publicActionResult StudentMvcWithKnockout() {  
        Student student = new Student();  
        student.Number = "B123456";  
        student.Name = "Peter";  
        student.Surname = "Scott";  
        return View(student);  
    }  
    //View:  
      
    @using System.Web.Script.Serialization;  
    @model MvcAppWithJquery.Models.Student  
    @ {  
        ViewBag.Title = "StudentMvcWithKnockout";  
        Layout = "~/Views/Shared/_Layout.cshtml";  
    }  
    <h2>StudentMvcWithKnockout</h2> <  
    scriptsrc = "../../Scripts/knockout-2.1.0.js"  
    type = "text/javascript" > < /script> <  
    scriptsrc = "../../Scripts/knockout.mapping-latest.js"  
    type = "text/javascript" > < /script> <  
    p > Name: < strongdata - bind = "text: Name" > < /strong></p >  
        <p>SurName:<strongdata-bind="text: Surname"></strong></p> <  
        scripttype = "text/javascript" >  
        $(function() {  
            var model = @Html.Raw(Json.Encode(Model));  
            ko.applyBindings(model);  
        }); <  
    /script>  


By calling ko.mapping in the view, we can access JSON data. But we must pass the JSON data from the controller by "return Json(StudentList,JsonRequestBehavior.AllowGet);". So we need a number of collections on ViewModel. We call "ko.applyBindings(viewModel) - so" simply using:
$(document).ready(function () { ko.applyBindings(viewModel); });
 
The $.ajax and $.getJSON methods are appropriate to get the JSON data. (Controller/Action) You can find two methods in the source code.


Code:
    // Controller  
    public JsonResult GetStudents()  
    {  
    List<Student> StudentList = newList<Student>(){new Student(){ Number="A123456", Name="Alexander", Surname="Leon"},  
            new Student(){ Number="B123456", Name="Peter", Surname="Scott"},  
            new Student(){ Number="C123456", Name="Michael", Surname="Leroy"},  
            new Student(){ Number="D123456", Name="Frank", Surname="Mill"}};  
            return Json(StudentList,JsonRequestBehavior.AllowGet);  
            }  
            // View  
            <tbody data-bind="foreach: Students">  
                <tr style="border-bottom: 1px solid #000000;">  
                    <td>  
                        <span data-bind="text: Number"></span>  
                    </td>  
                    <td>  
                        <span data-bind="text: Name"></span>  
                    </td>  
                    <td>  
                        <span data-bind="text: Surname"></span>  
                    </td>  
                </tr>  
            </tbody>  
            </table>  
            </div>  
            </form>  
            <script type="text/javascript">  
            var AppViewModel = function() {  
                var self = this;  
                self.Students = ko.mapping.fromJS([]);  
                $.getJSON('/Student/GetStudents/', function(data) { ko.mapping.fromJS(data, {}, self.Students); });  
            }  
            $(document).ready(function() {  
                var viewModel = new AppViewModel();  
                ko.applyBindings(viewModel);  
            });  
            </script>  

Review of Codes
"self.Students = ko.mapping.fromJS([]);" is an important one because "mapping from What?" is necessary. Mapping is controlled by Js. Calling'/Student/GetStudents/' we can feed the ViewModel.
You should use "$.getJSON" and "$.ajax" to get the JSON data.
Using "ko.mapping.fromJS(data, {}, self.Students);" you can fill the "self.Students" ViewModel using data that is in the JSON format.

Summary
KO can help you implement it easier and improve maintainability. Model Changes are observed by the ViewModel and updated UI parts. KO is a simple way to connect the UI from the Data Model. You can charge data procedures on KO so other js events (Click, Mouseover, Grid etc.) can be developed by using jQuery. KO is a pure JavaScript library that works with any server and client-side technology. KO provides a way to use MVVM on MVC technology. KO provides a complimentary, high-level way to link a data model to a UI.



ASP.NET MVC Hosting - HostForLIFE.eu :: Using SMTP to Send Emails in ASP.NET Core MVC

clock September 26, 2024 08:10 by author Peter

Assume you are creating a system for booking travel, and when a user books a car, two emails are sent.

  • Service email: Sent with information about the reservation to the firm.
  • Customer email: Submitted to the client as a reservation confirmation.

The use of the MailMessage and SmtpClient classes to do this is demonstrated in the C# code that follows.

This article explains how to combine the HTML form that is provided, the C# backend mail-sending code, and AJAX capability that uses jQuery to transfer form data to the server. I've included the necessary cshtml code that includes validation, Ajax integration, and captcha features.

Code Breakdown
CSHTML with AJAX Integration
<div class="booking_content">
    <h2>Reserve Your Ride Online</h2>
    <form action="" method="post" id="booking_form" novalidate="novalidate" class="row booking_form">
        <div class="col-md-6">
            <div class="form-group">
                <input type="text" class="form-control" name="name" placeholder="&#xe08a  Your Name">
                <label class="border_line"></label>
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <input type="text" class="form-control" name="subject" placeholder="&#xe06b  Subject">
                <label class="border_line"></label>
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <input type="text" class="form-control" name="email" placeholder="&#xe090  Your Email">
                <label class="border_line"></label>
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <input type="text" class="form-control" name="mobile" placeholder="&#xe090  Phone">
                <label class="border_line"></label>
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <input type="text" class="form-control" name="stratdestination" placeholder="&#xe01d  Start Destination">
                <label class="border_line"></label>
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <input type="text" class="form-control" name="endDestination" placeholder="&#xe01d  End Destination">
                <label class="border_line"></label>
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <input type="text" class="form-control date-input-css" name="timedate" placeholder="&#xe06b  Time and Date">
                <label class="border_line"></label>
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <select class="form-control" name="cartype">
                    <option>--Select Car Type--</option>
                    <option value="A/C Tata Indigo">A/C Tata Indigo</option>
                    <!-- Add other car types -->
                </select>
                <label class="border_line"></label>
            </div>
        </div>
        <div class="col-sm-6 col-md-6">
            <div class="form-group row">
                <label class="col-sm-4 col-md-3 control-label">
                    <div id="divGenerateRandomValues"></div>
                </label>
            </div>
        </div>
        <div class="col-sm-6 col-md-6">
            <div class="form-group row">
                <input type="text" id="textInput" class="form-control" placeholder="Enter Captcha" />
                <span class="errCap text-danger"></span>
            </div>
        </div>
        <div class="col-lg-12">
            <div class="form-group">
                <button type="submit" value="submit" class="btn slider_btn dark_hover btnBookNow" id="btnSubmit">Book Now</button>
            </div>
        </div>
    </form>
</div>

<!-- Modal -->
<div class="modal fade sccmodl" id="sccmodl" tabindex="1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5>Booking Information</h5>
                <button type="button" class="close No" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <h6 class="indxmsg"></h6>
            </div>
            <div class="modal-footer">
                <input type="button" class="btn btn-info btn-sm btnOk" value="Ok" />
            </div>
        </div>
    </div>
</div>


@section Scripts {
    <script type="text/javascript">
        var iNumber = Math.floor(1000 + Math.random() * 9000);

        $(document).ready(function () {
            $("#btnSubmit").prop("disabled", true);
            $("#divGenerateRandomValues").html("<input id='txtNewInput' value='" + iNumber + "' disabled/>");

            // Validate Captcha
            $("#btnSubmit").click(function (e) {
                e.preventDefault();
                if ($("#textInput").val() != iNumber) {
                    $('.errCap').text('Invalid Captcha !');
                } else {
                    $('.errCap').text('');
                    submitForm();
                }
            });

            var wrongInput = function () {
                return $("#textInput").val() != iNumber;
            };

            $("#textInput").bind('input', function () {
                $("#btnSubmit").prop('disabled', wrongInput);
            });
        });

        function submitForm() {
            $('#booking_form').validate({
                rules: {
                    name: { required: true, minlength: 2 },
                    subject: { required: true, minlength: 4 },
                    email: { required: true, email: true },
                    mobile: { required: true, minlength: 10, maxlength: 10, number: true },
                    stratdestination: { required: true, minlength: 2 },
                    endDestination: { required: true, minlength: 2 },
                    timedate: { required: true },
                    cartype: { required: true }
                },
                messages: {
                    name: { required: "Enter your name", minlength: "At least 2 characters" },
                    subject: { required: "Enter a subject", minlength: "At least 4 characters" },
                    email: { required: "Enter a valid email" },
                    mobile: { required: "Enter a valid phone number", minlength: "10 characters" },
                    stratdestination: { required: "Enter a start destination" },
                    endDestination: { required: "Enter an end destination" },
                    timedate: { required: "Select a date" },
                    cartype: { required: "Select a car type" }
                },
                submitHandler: function (form) {
                    $.ajax({
                        type: "POST",
                        url: "/Home/SendMail",
                        data: $(form).serialize(),
                        success: function (response) {
                            $('#sccmodl').modal('show');
                            $('.indxmsg').html(response);
                        },
                        error: function () {
                            alert("Error in sending the form.");
                        }
                    });
                }
            });
        }
    </script>
}


1. SendMail Action
Here’s the main controller action that handles the sending of the emails.
[HttpPost]
public ActionResult SendMail(string name, string email, string mobile, string subject, string timedate, string stratdestination, string endDestination, string cartype)
{
    try
    {
        // Create mail messages
        MailMessage mail = new MailMessage();
        MailMessage forCustomer = new MailMessage();
        SmtpClient smtpClient = new SmtpClient("mail.prakash.in", 587);

        // Configure SMTP client
        smtpClient.UseDefaultCredentials = false;
        smtpClient.Credentials = new NetworkCredential("[email protected]", "Bmbn0Dn26g6i~kybW");
        smtpClient.EnableSsl = false;

        // Configure mail for service
        mail.To.Add("[email protected]");
        mail.Bcc.Add("[email protected]");
        mail.From = new MailAddress("[email protected]", "Company Name");
        mail.Subject = subject;
        mail.Body = GenerateServiceMailBody(name, email, mobile, subject, timedate, stratdestination, endDestination, cartype);
        mail.IsBodyHtml = true;

        // Configure mail for customer
        forCustomer.To.Add(email);
        forCustomer.From = new MailAddress("[email protected]", "Company Name");
        forCustomer.Subject = subject;
        forCustomer.Body = GenerateCustomerMailBody(name);
        forCustomer.IsBodyHtml = true;

        // Send emails
        smtpClient.Send(mail);
        smtpClient.Send(forCustomer);

        return Json("Mail sent successfully! Please check your mail.");
    }
    catch (SmtpException smtpEx)
    {
        // Log detailed SMTP exception
        return Json($"SMTP Error: {smtpEx.Message}");
    }
    catch (Exception ex)
    {
        // Log general exception
        return Json($"Error: {ex.Message}");
    }
}


Explanation
SMTP Configuration: The SMTP client is configured using the SmtpClient class. In this case, it uses the mail.prakash.in the SMTP server on port 587, and the credentials for the email account are provided.
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential("[email protected]", "Bmb~kybW");
smtpClient.EnableSsl = false;


Sending Emails to Multiple Recipients
Two separate emails are created.

  • The first email is sent to the company (service email) with the customer's booking details.
  • The second email is a confirmation sent to the customer.


Both emails are sent using smtpClient.Send(mail).

2. HTML Email Templates

HTML-formatted emails are used to send user-friendly content. Here, we generate two different types of email bodies: one for the service and one for the customer.

Service Email Template
private string GenerateServiceMailBody(string name, string email, string mobile, string subject, string timedate, string stratdestination, string endDestination, string cartype)
{
    return "<table cellspacing='0'>" +
        "<tr><td colspan='2'>Your contact person details:<br/></td></tr>" +
        "<tr><td colspan='2'><b><br/> Name: " + name + " <br/> Email: " + email + " <br/> Mobile: " + mobile + "  <br/> Subject: " + subject + "  <br/> Booking Date: " + timedate + " <br/> Start Destination: " + stratdestination + " <br/> End Destination: " + endDestination + " <br/> Booking Car: " + cartype + "  </b></td></tr>" +
        "<tr><td colspan='2'><br/>Please contact above person as soon as possible.<br />Thanks!</td></tr>" +
        "</table>";
}


Customer Email Template
private string GenerateCustomerMailBody(string name)
{
    return "<table cellspacing='0'>" +
        "<tr><td colspan='2'>Hello ,<br/></td></tr>" +
        "<tr><td colspan='2'><b><br/>  " + name + "    </b></td></tr>" +
        "<tr><td colspan='2'><br/>Thanks for your email. </td></tr>" +
        "<tr><td colspan='2'><br/>Please connect with us. </td></tr>" +
        "</table>";
}

The email sent to the customer confirms that their booking has been received and includes a personalized greeting.

3. Error Handling

Error handling is an essential aspect when dealing with external services like SMTP. Two exception blocks are used:

  • SmtpException: Catches issues related to SMTP (e.g., wrong credentials, SMTP server down).
  • Exception: A general catch block for any other issues that may arise.


catch (SmtpException smtpEx)
{
    return Json($"SMTP Error: {smtpEx.Message}");
}
catch (Exception ex)
{
    return Json($"Error: {ex.Message}");
}

Conclusion
This approach enables sending structured HTML emails from an ASP.NET MVC application using MailMessage and SmtpClient. You can easily customize the email templates, manage multiple recipients, and handle errors effectively.

When working with sensitive information like email credentials, it’s essential to avoid hardcoding them in the source code. Instead, store these values securely in a configuration file, like web.config, or use environment variables for improved security.

By following this structure, you can seamlessly add email functionality to your MVC applications and provide a smooth experience for both service providers and customers.



ASP.NET MVC Hosting - HostForLIFE.eu :: Full Upload and Download of Files in ASP.NET Core MVC

clock September 2, 2024 08:15 by author Peter

A strong framework that enables creating web apps quick and simple is ASP.NET Core MVC. Users must upload and download files to and from the server in numerous real-world situations. In this post, we'll create a basic ASP.NET Core MVC application with file upload and download capabilities.


1. Establishing the Project
Start by using Visual Studio or the.NET CLI to build a new ASP.NET Core MVC project.

Making Use of CLI

dotnet new mvc -n FileUploadDownloadApp
cd FileUploadDownloadApp


Using Visual Studio

  • Open Visual Studio and create a new project.
  • Select "ASP.NET Core Web App (Model-View-Controller)".
  • Name it FileUploadDownloadApp.

2. Creating the Model
The next step is to create a model that represents the file to be uploaded. We will store the uploaded file in an IFormFile object.
public class FileUploadViewModel
{
    public IFormFile File { get; set; }
}


The IFormFile interface represents the uploaded file in the HTTP request.

3. Creating the Controller
The controller handles user requests to upload and download files. Create a new FileController with actions for file upload, file listing, and file download.

using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Threading.Tasks;
using FileUploadDownloadApp.Models;
using Microsoft.AspNetCore.Hosting;

public class FileController : Controller
{
    private readonly IWebHostEnvironment _environment;
    public FileController(IWebHostEnvironment environment)
    {
        _environment = environment;
    }
    // GET: File/Upload
    public IActionResult Upload()
    {
        return View();
    }
    // POST: File/Upload
    [HttpPost]
    public async Task<IActionResult> Upload(FileUploadViewModel model)
    {
        if (model.File != null && model.File.Length > 0)
        {
            // Define the upload folder
            string uploadPath = Path.Combine(_environment.WebRootPath, "uploads");
            // Create the folder if it doesn't exist
            if (!Directory.Exists(uploadPath))
            {
                Directory.CreateDirectory(uploadPath);
            }
            // Generate the file path
            string filePath = Path.Combine(uploadPath, model.File.FileName);
            // Save the file to the specified location
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await model.File.CopyToAsync(stream);
            }
            ViewBag.Message = "File uploaded successfully!";
        }
        return View();
    }
    // GET: File/ListFiles
    public IActionResult ListFiles()
    {
        string uploadPath = Path.Combine(_environment.WebRootPath, "uploads");
        if (!Directory.Exists(uploadPath))
        {
            return View(new List<string>());
        }
        var files = Directory.GetFiles(uploadPath).Select(Path.GetFileName).ToList();
        return View(files);
    }
    // GET: File/Download?filename=example.txt
    public IActionResult Download(string filename)
    {
        if (string.IsNullOrEmpty(filename))
        {
            return Content("Filename is not provided.");
        }
        string filePath = Path.Combine(_environment.WebRootPath, "uploads", filename);
        if (!System.IO.File.Exists(filePath))
        {
            return Content("File not found.");
        }
        byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
        return File(fileBytes, "application/octet-stream", filename);
    }
}

Breakdown

  • Upload: Saves uploaded files to the /uploads directory in wwwroot.
  • ListFiles: Displays a list of uploaded files.
  • Download: Allows downloading files from the server by providing the file name as a query parameter.


4. Creating Views
Upload View (Upload. cshtml)
@model FileUploadViewModel
<h2>Upload File</h2>
<form asp-action="Upload" enctype="multipart/form-data" method="post">
    <div class="form-group">
        <input type="file" asp-for="File" class="form-control" />
    </div>
    <button type="submit" class="btn btn-primary">Upload</button>
</form>
@if (ViewBag.Message != null)
{
    <p>@ViewBag.Message</p>
}


List Files View (ListFiles.cshtml)
@model List<string>
<h2>Uploaded Files</h2>
<table class="table">
    <thead>
        <tr>
            <th>File Name</th>
            <th>Download</th>
        </tr>
    </thead>
    <tbody>
    @foreach (var file in Model)
    {
        <tr>
            <td>@file</td>
            <td>
                <a asp-action="Download" asp-route-filename="@file" class="btn btn-success">Download</a>
            </td>
        </tr>
    }
    </tbody>
</table>

5. Navigation in Layout
To make file upload and download pages easily accessible, add links to these views in the main layout file (_Layout. cshtml).
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - FileUploadDownloadApp</title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/FileUploadDownloadApp.styles.css" asp-append-version="true" />
</head>
<body>
    <header>
        <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
            <div class="container">
                <a class="navbar-brand" asp-area="" asp-page="/Index">FileUploadDownloadApp</a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                    <ul class="navbar-nav flex-grow-1">
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-controller="Home" asp-action="Upload">Upload File</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-controller="Home" asp-action="ListFiles">List Files</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
    </header>
    <div class="container">
        <main role="main" class="pb-3">
            @RenderBody()
        </main>
    </div>

    <footer class="border-top footer text-muted">
        <div class="container">
            &copy; 2024 - FileUploadDownloadApp - <a asp-area="" asp-page="/Privacy">Privacy</a>
        </div>
    </footer>

    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>

    @await RenderSectionAsync("Scripts", required: false)
</body>
</html>


6. Running and Testing the Application
Once you've added the controller, views, and navigation links, run the application.

  • Upload Files: Navigate to /File/Upload to upload files.
  • List Files: After uploading, go to /File/ListFiles to see all uploaded files.
  • Download Files: Click the "Download" button to download the files.

7. Security and Best Practices
When implementing file upload and download functionality, security should be a top priority.File Size Limitations: Enforce limits on file size to prevent large files from overwhelming the server.services.Configure<FormOptions>(options => options.MultipartBodyLengthLimit = 10485760); // 10MBValidate File Types: Only allow certain file types by checking the file extension or MIME type.var allowedExtensions = new[] { ".jpg", ".png", ".pdf" };
var extension = Path.GetExtension(model.File.FileName);
if (!allowedExtensions.Contains(extension))
{
    ModelState.AddModelError("File", "Unsupported file type.");
}

Sanitize File Names: Remove any unwanted characters from file names before saving them.var safeFileName = Path.GetFileNameWithoutInvalidChars(model.File.FileName);Limit Upload Folder Access: Restrict access to the upload folder to prevent unauthorized access. Only allow authenticated users to download files if necessary.

8. Output


Conclusion
In order to manage file upload and download, we constructed a straightforward ASP.NET Core MVC application in this tutorial. To keep the application safe, we went over the fundamentals of building models, controllers, and views as well as security recommended practices. By incorporating features like progress bars, database storage for file information, or even Azure blob storage integration for managing larger files in cloud environments, you may further develop the application with this knowledge.



ASP.NET MVC Hosting - HostForLIFE.eu :: How to Mapping with Conditional Display in a ASP.NET MVC Application?

clock August 27, 2024 07:47 by author Peter

Keeping resumes organized across several job vacancies is essential in the recruitment business. This blog post explores the effective mapping of resumes to various job listings within a.NET MVC application. We'll go over the structure of the database, the reasoning needed to link resumes to job IDs, and the procedures to make sure that resumes associated with closed jobs are removed from consideration for open positions.

With the help of this guide, you will be able to optimize your job and resume management process in.NET MVC, regardless of whether you're creating a recruiting portal or improving existing HR administration system.

Here's how to approach your.NET MVC project to meet the requirements.

1. Database Design

  • Job Table
    • JobID (Primary Key)
    • JobStatus (e.g., Active, Closed)
  • Resume Table
    • ResumeID (Primary Key)
    • Other resume details.
  • JobResumeMapping Table
    • JobID (Foreign Key to Job Table)
    • ResumeID (Foreign Key to Resume Table)
    • MappingID (Primary Key for the table)

2. Mapping Resumes to Different Job IDs
You would create or update records in the JobResumeMapping table to map resumes to different jobs.
Example method to map a resume to a job.

public void MapResumeToJob(int jobId, int resumeId)
{
    using (var context = new YourDbContext())
    {
        var mapping = new JobResumeMapping
        {
            JobID = jobId,
            ResumeID = resumeId
        };
        context.JobResumeMappings.Add(mapping);
        context.SaveChanges();
    }
}

3. Preventing Resume from Showing in Other Jobs once the Job is closed
You should filter out resumes mapped to closed jobs.
Example of how to do it in a query.

    var openJobsWithResumes = context.JobResumeMappings
                                      .Where(jrm => jrm.Job.JobStatus == "Active")
                                      .Include(jrm => jrm.Resume)
                                      .ToList();


Alternatively, you can use a method to update the status of the job and remove the mapping.
public void CloseJob(int jobId)
{
    using (var context = new YourDbContext())
    {
        var job = context.Jobs.Find(jobId);
        if (job != null)
        {
            job.JobStatus = "Closed";
            context.SaveChanges();
        }
    }
}


4. Ensure UI Logic
In your view, only show resumes linked to jobs that are not closed.

@foreach (var job in Model.Jobs)
{
    if (job.JobStatus == "Active")
    {
        // Display resumes mapped to this job
    }
}

5. Additional Considerations
To preserve referential integrity, you could also choose to use update operations or cascade deletes. The mappings must to be updated or eliminated in the event that a job is deleted.

6. Business Logic in the Controller

Make sure the logic for closing jobs and filtering resumes is handled by your controller methods.
Your demands for matching resumes to various jobs should be met by this configuration, which also makes sure that resumes linked to closed jobs are removed from consideration for open positions.



ASP.NET MVC Hosting - HostForLIFE.eu :: Managing Large Session States in ASP.NET MVC

clock August 20, 2024 07:10 by author Peter

It is crucial to adhere to recommended practices when working with big session states in ASP.NET MVC in order to guarantee optimum speed and scalability. The following are suggested best practices.


Minimize Session Data

Only keep the most important information in the session state. Steer clear of storing bulky items or intricate data structures that can needlessly expand the session size.

// Instead of storing a large object in the session
public IActionResult ActionName()
{
    var largeObject = GetLargeObject(); // Assuming this returns a large object
    HttpContext.Session.SetObject("LargeObject", largeObject); // Avoid storing large objects

    // Store only the essential data
    HttpContext.Session.SetString("UserName", "csharpcorner");
    HttpContext.Session.SetInt32("Age", 25);

    return View();
}

Use Serializable Objects
Ensure that the objects you store in the session state are serializable. This means that the objects can be converted to a stream of bytes for storage and later deserialized when needed.

[Serializable]
public class UserData
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public IActionResult ActionName()
{
    var userData = new UserData
    {
        Name = "Hostforlife",
        Age = 25
    };

    HttpContext.Session.SetObject("UserData", userData);

    return View();
}


Implement Session State Compression
ASP.NET provides built-in support for compressing session data before storing it. This can significantly reduce the size of the session state. You can enable compression in the web.config.
<system.web>
  <sessionState mode="InProc" compressionEnabled="true" />
</system.web>


Use a Distributed Cache
Instead of storing large session data on the server, consider using a distributed cache like Redis or Memcached. These caching solutions can store session data more efficiently and provide better scalability for web farm scenarios.

Install the necessary NuGet packages (e.g., Microsoft.Extensions.Caching.Redis) and configure the distributed cache in the Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddDistributedRedisCache(options =>
    {
        options.Configuration = "localhost:6379"; // Redis server connection string
    });

    // Other service configurations
}

Then, use the distributed cache in your controller actions.
public IActionResult CacheAction(IDistributedCache cache)
{
    var userData = new UserData
    {
        Name = "Hostforlife",
        Age = 25
    };

    cache.SetString("UserData", JsonConvert.SerializeObject(userData));

    // Retrieve the cached data

    return View();
}


Implement Session State Expiration
Set appropriate expiration times for session data to ensure that stale data is removed from the session state. This can help reduce the overall size of the session state.
public void ConfigureServices(IServiceCollection services)
{
    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromMinutes(30); // Session will expire after 30 minutes of inactivity
    });

    // Other service configurations
}

Use Asynchronous Session State
ASP.NET provides an asynchronous session state option that can improve performance by allowing other requests to be processed while waiting for session state operations to complete.
public async Task<IActionResult> AsyncAction()
{
    await HttpContext.Session.LoadAsync();

    // Perform session state operations asynchronously
    HttpContext.Session.SetString("UserName", "Hostforlife");

    return View();
}


Implement Caching Strategies
Implement caching strategies to reduce the need for storing large amounts of data in the session state. For example, you can cache frequently accessed data in memory or use a distributed cache.

Conclusion

In order to manage file upload and download, we constructed a straightforward ASP.NET Core MVC application in this tutorial. To keep the application safe, we went over the fundamentals of building models, controllers, and views as well as security recommended practices.



ASP.NET MVC Hosting - HostForLIFE.eu :: Understanding MVC in ASP.NET Core

clock August 13, 2024 09:22 by author Peter

Model-View-Controller (MVC) is a design pattern that has been widely used in software engineering for creating well-structured and maintainable applications. In the context of .NET Core, MVC provides a robust framework for building web applications, separating concerns between the data (model), the user interface (view), and the business logic (controller).

This article will delve into what MVC is, how it works in .NET Core, and how you can build a simple MVC application.

What is MVC?
MVC stands for Model-View-Controller, a pattern that divides an application into three interconnected components.

Model

  • Represents the data and the business logic of the application.
  • Directly manages the data, logic, and rules of the application.
  • In .NET Core, the model can be an entity class that represents data in the database.

View

  • Represents the presentation layer of the application.
  • Responsible for displaying the data provided by the model in a user-friendly format.
  • Views in .NET Core are typically Razor files (.cshtml) that generate HTML dynamically.

Controller

  • Acts as an intermediary between the Model and the View.
  • Handles user input, processes it using the model, and returns the appropriate view.
  • In .NET Core, controllers are classes that inherit from the Controller and contain action methods.

How does MVC Work in .NET Core?
When a user interacts with an MVC application, the flow of control follows these steps.

User Request: The user sends a request, such as clicking a link or submitting a form.
Controller Action: The request is routed to a controller action method. The controller processes the request, interacts with the model if necessary, and selects a view to render.
View Rendering: The view receives the data from the controller and generates the HTML to be displayed to the user.
Response: The HTML generated by the view is sent back to the user's browser, where it is rendered.

Creating a Simple MVC Application in .NET Core
Let's walk through creating a simple MVC application in .NET Core.

Step 1. Setting Up the Project

You can start by creating a new MVC project in .NET Core using Visual Studio or the .NET CLI.
dotnet new mvc -n MvcDemoApp

This command creates a new MVC project named MvcDemoApp.

Step 2. Understanding the Project Structure
In an MVC project, you'll find three main folders.

  • Models: Contains the classes that represent the application's data and business logic.
  • Views: Contains the .cshtml files that define the HTML structure of the application.
  • Controllers: Contains the controller classes that manage the flow of the application.

Step 3. Creating a Model
Let's create a simple model that represents a product.
namespace MvcDemoApp.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
}
Step 4. Creating a ControllerNext, create a controller to handle requests related to products.
using Microsoft.AspNetCore.Mvc;
using MvcDemoApp.Models;

namespace MvcDemoApp.Controllers
{
    public class ProductsController : Controller
    {
        public IActionResult Index()
        {
            var products = new List<Product>
            {
                new Product { Id = 1, Name = "Laptop", Price = 1200 },
                new Product { Id = 2, Name = "Smartphone", Price = 800 }
            };

            return View(products);
        }
    }
}
The Index action method returns a list of products to the view.
Step 5. Creating a View
Finally, create a view to display the list of products. Add an Index.cshtml file under Views/Products.@model IEnumerable<MvcDemoApp.Models.Product>

<h2>Product List</h2>

<table class="table">
    <thead>
        <tr>
            <th>Name</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var product in Model)
        {
            <tr>
                <td>@product.Name</td>
                <td>@product.Price</td>
            </tr>
        }
    </tbody>
</table>

This view displays the product data in an HTML table.

Step 6. Running the Application
Benefits of Using MVC

  • Separation of Concerns: MVC promotes a clear separation between the application's concerns, making it easier to manage and scale.
  • Reusability: The separation of concerns allows for more reusable code components.
  • Testability: The MVC pattern enhances the testability of your application by decoupling the components.

Conclusion
The MVC pattern in .NET Core provides a clean and organized way to develop web applications by separating the application into three core components: Model, View, and Controller. This separation makes your application more manageable, scalable, and testable. By following the steps outlined in this article, you can start building your own MVC applications in .NET Core and take advantage of the powerful features it offers.

 



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