European ASP.NET MVC 4 and MVC 5 Hosting

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

ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Kendo Grid in ASP.NET MVC Using Helpers

clock September 29, 2026 12:04 by author Peter

When building web applications, we often need to display data in a table format with features like:

  • Paging
  • Sorting
  • Filtering
  • Editing

Instead of writing complex code, we can use Kendo UI Grid.
Kendo Grid is a powerful UI component that helps display data easily with built-in features.
In this article, we will learn:

  • What Kendo Grid is
  • Why we use it
  • How to use Kendo Grid in MVC using Helpers
  • All important features with simple examples

What is Kendo Grid?
Kendo Grid is a UI component from Progress Telerik that helps display data in a table with advanced features.

Why Use Kendo Grid?

  • No need to write complex JavaScript
  • Built-in features (paging, sorting, filtering)
  • Clean UI
  • Easy to use with MVC

Step 1: Create Model
public class Student
{
    public int StudentId { get; set; }

    public string StudentName { get; set; }

    public string City { get; set; }
}


Step 2: Controller Code
public class StudentController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult GetStudents()
    {
        List<Student> list = new List<Student>()
        {
            new Student{ StudentId=1, StudentName="Peter", City="London"},
            new Student{ StudentId=2, StudentName="Scott", City="Liverpool"},
            new Student{ StudentId=3, StudentName="Leo", City="Leeds"}
        };

        return Json(list, JsonRequestBehavior.AllowGet);
    }
}


Step 3: Add Kendo Grid in View (Using Helpers)
@(Html.Kendo().Grid<Student>()
    .Name("StudentGrid")

    .Columns(columns =>
    {
        columns.Bound(p => p.StudentId).Title("ID");
        columns.Bound(p => p.StudentName).Title("Name");
        columns.Bound(p => p.City).Title("City");
    })

    .Pageable()

    .Sortable()

    .Filterable()

    .Scrollable()

    .DataSource(dataSource => dataSource
        .Ajax()
        .Read(read => read.Action("GetStudents", "Student"))
    )
)


What is this?
Output

Grid will show:

ID   Name     City
1    Peter    Londo
2    Scott    Liverpool
3    Leo       Leeds

With:

  • Paging
  • Sorting
  • Filtering

Important Kendo Grid Features (All Methods Explained)
1. Columns
columns.Bound(p => p.StudentName).Title("Name");

Used to define columns

2. Pageable()
.Pageable()

Adds pagination

3. Sortable()
.Sortable()

Enable column sorting

4. Filterable()

.Filterable()

Add filter option

5. Groupable()
.Groupable()

Group data by column

6. Scrollable()
.Scrollable()

Enable scrolling

7. Editable()
.Editable(editable => editable.Mode(GridEditMode.InLine))

Enable inline editing

8. Toolbar
.ToolBar(toolbar => toolbar.Create())

Add "Create" button

9. Command Column
columns.Command(command =>
{
    command.Edit();
    command.Destroy();
});

Add Edit/Delete buttons

10. DataSource
.DataSource(dataSource => dataSource
    .Ajax()
    .Read(read => read.Action("GetStudents", "Student"))
)

Connect grid with controller

Full CRUD Example

@(Html.Kendo().Grid<Student>()
    .Name("Grid")

    .Columns(columns =>
    {
        columns.Bound(p => p.StudentId).Editable(false);
        columns.Bound(p => p.StudentName);
        columns.Bound(p => p.City);

        columns.Command(command =>
        {
            command.Edit();
            command.Destroy();
        });
    })

    .ToolBar(toolbar => toolbar.Create())

    .Editable(editable => editable.Mode(GridEditMode.InLine))

    .Pageable()
    .Sortable()
    .Filterable()

    .DataSource(dataSource => dataSource
        .Ajax()
        .Model(model =>
        {
            model.Id(p => p.StudentId);
        })
        .Read(read => read.Action("GetStudents", "Student"))
        .Create(create => create.Action("Create", "Student"))
        .Update(update => update.Action("Update", "Student"))
        .Destroy(delete => delete.Action("Delete", "Student"))
    )
)


What is this?
Controller CRUD Methods

public ActionResult Create(Student model)
{
    return Json(model);
}

public ActionResult Update(Student model)
{
    return Json(model);
}

public ActionResult Delete(Student model)
{
    return Json(model);
}


When to Use Kendo Grid?
Use Kendo Grid when:

  • Display large data
  • Need sorting/filtering
  • Want professional UI
  • CRUD operations required

Advantages

  • Fast development
  • Less coding
  • Built-in features
  • Professional UI

Conclusion
Kendo Grid is a powerful tool in ASP.NET MVC for displaying and managing data.

In this article, we learned:

  • How to use Kendo Grid with MVC Helpers
  • All important methods
  • CRUD operations
  • Real example


ASP.NET MVC 6 Hosting - HostForLIFE.eu :: ASP.NET MVC Return Types

clock September 23, 2026 13:40 by author Peter

In ASP.NET MVC, controller action methods return different types of results depending on what the application needs to send back to the browser. 

For example, an action method may return:

  • A View page
  • JSON data
  • A file download
  • Redirect to another page

These responses are called Action Results.

Understanding return types helps developers choose the correct response type when building web applications.

In this article, we will learn:

  • What return types are in ASP.NET MVC
  • Why they are used
  • Different return types with examples
  • When to use each return type

What is ActionResult?
ActionResult is the base class for all result types in ASP.NET MVC.
It allows a controller action method to return different types of responses.

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

Here the controller returns a ViewResult, but the return type is ActionResult.

This gives flexibility to return different results.

1. ViewResult
What is ViewResult?

ViewResult returns an HTML view page to the browser.

Example
Controller:
public ViewResult Index()
{
    return View();
}


View:
<h2>Welcome to ASP.NET MVC</h2>

What is this?
Output
Welcome to ASP.NET MVC

When to Use
Use ViewResult when you want to display a web page to the user.

2. PartialViewResult
What is PartialViewResult?
PartialViewResult returns a partial view instead of a full page.

Partial views are reusable UI components.

Example
public PartialViewResult Header()
{
    return PartialView("_Header");
}


When to Use
Use when loading small UI sections like:

  • Header
  • Footer
  • Sidebar
  • AJAX partial content

3. JsonResult
What is JsonResult?

JsonResult returns JSON data instead of HTML.

This is commonly used in AJAX calls.
Example
public JsonResult GetStudent()
{
    var student = new
    {
        Id = 1,
        Name = "Peter",
        Age = 20
    };

    return Json(student, JsonRequestBehavior.AllowGet);
}

Output
{
 "Id":1,
 "Name":"
Peter",
 "Age":20
}

When to Use
Use JsonResult when sending data to:

  • AJAX
  • JavaScript
  • APIs

4. ContentResult
What is ContentResult?

ContentResult returns plain text or HTML content.

Example
public ContentResult Message()
{
    return Content("Hello from ASP.NET MVC");
}

Output
Hello from ASP.NET MVC
When to Use


Use when returning simple text content.

5. FileResult
What is FileResult?

FileResult returns a file download to the browser.
Example
public FileResult Download()
{
    string path = Server.MapPath("~/Files/sample.pdf");

    return File(path, "application/pdf", "sample.pdf");
}


Output
The browser downloads sample.pdf.

When to Use
Use when allowing users to download:

  • PDF files
  • Excel files
  • Images
  • Documents

6. RedirectResult
What is RedirectResult?

RedirectResult redirects the browser to another URL.
Example
public RedirectResult GoToGoogle()
{
    return Redirect("https://www.google.com");
}

When to Use
Use when redirecting to an external website.

7. RedirectToRouteResult
What is RedirectToRouteResult?

RedirectToRouteResult redirects to another controller action.

Example
public ActionResult Test()
{
    return RedirectToAction("Index");
}


When to Use

Use when navigating between MVC actions.

Example:
After saving data → redirect to List page.

8. EmptyResult
What is EmptyResult?

EmptyResult returns nothing to the browser.

Example
public EmptyResult DoNothing()
{
    return new EmptyResult();
}


When to Use
Use when no response is needed.

Return Types Summary

Return TypePurpose
ActionResult Base return type
ViewResult Return view page
PartialViewResult Return partial view
JsonResult Return JSON data
ContentResult Return text content
FileResult Download files
RedirectResult Redirect to external URL
RedirectToRouteResult Redirect to another action
EmptyResult Return nothing

Real-World Example

Imagine a student management system.

Different return types may be used:

  • ViewResult → Show student list page
  • JsonResult → Send student data using AJAX
  • FileResult → Download student report
  • RedirectToAction → Redirect after saving student

Each return type serves a different purpose.

Best Practice
Most developers use ActionResult as the return type.

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


This provides flexibility to return different result types later.

Conclusion
Return types in ASP.NET MVC control how data is sent from the controller to the browser.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: HTML Helpers In ASP.NET MVC

clock September 18, 2026 12:31 by author Peter

HTML Assistance
HTML Controls are made by creating HTML markup using HTML Helpers. A method that returns an HTML string is called HTML Helper. HTML Helpers come in three different varieties:

Inline HTML Helpers: These are created by the @helper tag of Razor Syntax. These Helpers can be reused only on the same view.
Built-In HTML Helpers: These HTML Helpers are extension methods on the HtmlHelper class. These are categorized in to three parts:

  • Standard HTML Helpers: These helpers are used to create the most common types of HTML elements.
  • Strongly Typed HTML Helpers: The HTML is generated through Model Class Properties. These helpers work on lambda expression.
  • Templated HTML Helpers: These helpers defines what HTML elements are required to render based on properties of our Model class.

Custom HTML Helpers: You can also create your own custom helper methods by creating an extension method on the HtmlHelper class or by creating static methods within a utility class.

Step 1: Open the Visual Studio and select the “File” menu, New, then Project.

In the following figure select “Templates”, Visual C#, ASP.NET Web Application, and here I gave the name of project as “HTMLHelpersWithMVC.”
You can give the project name as you wish.
And then click on “OK” button.

In the following figure as you can see the default MVC will be selected, select MVC and then click “OK” button.

First, I want to create a Controller, so right click on "Controllers" folder and click on “Add”, then click on to Controller, to add a Controller.

Select the MVC 5 Controller - Empty.
Click on to the “Add” button to add a Controller.

Here I gave the “MyController” name to my Controller.
Click on to the “Add” button.
You can give the Controller name as you wish.

In the “MyController”, right click near return view(); to add a view.

In the following figure, the view name is by default Index, and Templates name is by default Empty (without model).
Click on “Add” button to add a view.

Here is the first of all we have taken in the Inline HTML Helpers example, where we can show the items in Inline format.

Now I’m going to create Built-In Type HTML Helpers:
Firstly, I’m using the Standard HTML Helpers like HTML text boxes, Password, Dropdown list, etc.

Now I’m going to create Strongly Typed HTML Helpers-
For this I need to create a Model using a Model folder, right click on to Models folder, click on “Add” button and add a class.


Select the class name and give the name of this class “UserModel”.
Click on to the “Add” button.

In the Model Class, we have to create two properties, EmployeeName and Password.

In the Model Class, we have to create two properties, EmployeeName and Password.

To demonstrate, I want to add a new Controller, so right click on the Controllers folder and click on Add. Click on Controller to add a new Controller.

Select the MVC 5 Controller - Empty.
Click on “Add” button to add a Controller.

So give the Controller name “SignInController”.
Click on “Add” button.

Here we need to create a particular view, right click near return view(); and click “Add View”.


The View name by default is Index and Template name by default is Empty.
Click on Add button.

 

In the RouteConfig.cs, change the Controller name, write the “SignIn”.
Now run the Project, press F5 key to run the project.


Now I’m going to create Templated HTML Helpers-
In MyController.cs, right click near return view(); to add a view.
The View Name is by default “Temp” and Template Name is by default Empty.
Click on to the “Add” button.

Change the Controller and action name according to the View and Controller name in the RouteConfig.cs file.


Now I’m going to create Custom HTML Helpers:
First of all we need to create a Controller, so right click on Controllers folder, select “Add” and then Controller to add a Controller.


Select the MVC 5 Controller - Empty.
Click on “Add” button to add a Controller.


So give the Controller name “CustomController”.
Click on “Add” button.

Now we need to create a class.
Right click on to the Project and choose “Add” and then click on “class” to add a Class.


Select the Class and give the “CustomClass” name of the class. 
Click on to the “Add” button.

In the “CustomController.cs”, we need to add a View, so right click near view and click on “Add View”. 


Click on the “Add” button.

In the view page take a button and a Label.
In the RouteConfig.cs, change the name of Controller and action.
Run the project by pressing F5.
The final output is here.



ASP.NET MVC Hosting - HostForLIFE.eu :: Minification and Bundling in.NET Core MVC

clock September 14, 2026 11:23 by author Peter

In this post, we'll discuss how to include bundling into our current.NET CORE MVC web application. First, you must click on the extension menu to add the Bundler and Minifier extensions to your project, as seen below.

 

Please restart Visual Studio after adding an extension to ensure it loads.

Now we will add a bundleconfig.json file in our project root by adding JSON file by choosing the add new items option.
[{  
    "outputFileName": "wwwroot/js/site.min.js",  
    "inputFiles": ["wwwroot/lib/jquery/dist/jquery.js", "wwwroot/datatables/js/jquery.dataTables.js", "wwwroot/datatables/js/dataTables.bootstrap.js", "wwwroot/datatables/js/dataTables.bootstrap4.js", "wwwroot/datatables/js/dataTables.dataTables.js", "wwwroot/datatables/js/dataTables.foundation.js", "wwwroot/datatables/js/dataTables.jqueryui.js", "wwwroot/datatables/js/dataTables.material.js", "wwwroot/datatables/js/dataTables.semanticui.js", "wwwroot/datatables/js/dataTables.uikit.js", "wwwroot/datatables/js/datatables-buttons/js/dataTables.buttons.js", "wwwroot/datatables/js/datatables-buttons/js/buttons.colVis.js", "wwwroot/datatables/js/datatables-buttons/js/buttons.flash.js", "wwwroot/datatables/js/datatables-buttons/js/buttons.html5.js", "wwwroot/datatables/js/datatables-buttons/js/buttons.print.js"],  
    "minify": {  
        "enabled": true,  
        "renameLocals": true  
    }  
}, {  
    "outputFileName": "wwwroot/js/site.min.css",  
    "inputFiles": ["wwwroot/datatables/css/jquery.dataTables.css", "wwwroot/datatables/css/dataTables.bootstrap.css", "wwwroot/datatables/css/dataTables.bootstrap4.css", "wwwroot/datatables/css/dataTables.foundation.css", "wwwroot/datatables/css/dataTables.jqueryui.css", "wwwroot/datatables/css/dataTables.material.css", "wwwroot/datatables/css/dataTables.semanticui.css", "wwwroot/datatables/css/dataTables.uikit.css", "wwwroot/datatables/css/buttons.dataTables.min.css"],  
    "minify": {  
        "enabled": true,  
        "renameLocals": true  
    }  
}]  

As you have observed there are many files registered here so now we will add all these files to our wwwroot folder by adding client-side library after right-clicking on wwwroot folder.

Datatables-buttons folder is added separately by using the same procedure. Now let's minify and make the bundle as one file by following below process shown in screen shot.
Open task runner explorer by right-clicking on bundleconfig.json.

In Task runner right-click or double click on update all files; after doing this your output file mentioned in bundleconfig,json will be created in a mentioned path as shown below.

Output will be a file created like this if not please reload your project once.


Add CSS and JS file to your .cshtml page or _layout page.
<script src="~/js/site.min.js" asp-append-version="true"></script>    
 <link href="~/js/site.min.css" rel="stylesheet" asp-append-version="true" />    

That's it now run your page.

Summary
Bundling and Minification helps us to make our script and CSS minified and use that in a bundle.
Hope this helps, and Happy Coding.



ASP.NET MVC Hosting - HostForLIFE.eu :: CRUD Functions in an MVC.NET Core Project

clock September 9, 2026 11:45 by author Peter

CRUD stands for Create, Read, Update, and Delete. These four operations form the foundation of many data-driven web applications. In this article, we will build a simple ASP.NET Core MVC application that performs CRUD operations for a Students entity. We will create the project, define the model, configure the application, create a controller, and test the CRUD endpoints.

The example uses an in-memory collection to keep the implementation simple and focused on understanding the CRUD flow. A SQL Server or another database can be introduced later when persistent data storage is required.

Prerequisites
Before we begin, ensure you have the following:

  • Visual Studio 2022 or later.
  • .NET SDK.
  • Basic knowledge of C# and ASP.NET Core MVC.
  • Basic understanding of HTTP methods such as GET, POST, PUT, and DELETE.

Step 1: Setting Up the ASP.NET Core Project

  • Open Visual Studio.
  • Select Create a new project.
  • Search for ASP.NET Core Web API.
  • Select the ASP.NET Core Web API template and click Next.
  • Configure the project name and location.
  • Select the required .NET version.
  • Keep the default OpenAPI support enabled if you want to test the API through Swagger.
  • Click Create.

For this example, the project is named:
CRUDOperationAPI

Although the original example refers to an MVC project, the supplied StudentsController inherits from ControllerBase and uses [ApiController], which makes it an ASP.NET Core Web API controller. Therefore, this implementation follows the Web API approach.

Step 2: Configure the Project

For a basic CRUD API, the default project configuration is sufficient.

A typical Program.cs file looks like this:
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();


Here:

  • AddControllers() registers controller support.
  • AddEndpointsApiExplorer() enables API endpoint discovery.
  • AddSwaggerGen() generates OpenAPI documentation.
  • UseSwagger() and UseSwaggerUI() provide a browser-based interface for testing the API.
  • MapControllers() maps controller routes.

Step 3: Create the Student Model
Create a Models folder in the project.
Inside the folder, create a Students.cs class:
namespace CRUDOperationAPI.Models
{
    public class Students
    {
        public int Id { get; set; }

        public string Name { get; set; } = string.Empty;

        public int Age { get; set; }

        public string Address { get; set; } = string.Empty;
    }
}

This class represents the data that our CRUD API will manage.

The properties are:

Property

Description

Id

Unique identifier for the student

Name

Student's name

Age

Student's age

Address

Student's address

Step 4: Create the Students Controller
Create a StudentsController.cs file inside the Controllers folder.

The controller will expose endpoints for all four CRUD operations.
using CRUDOperationAPI.Models;
using Microsoft.AspNetCore.Mvc;

namespace CRUDOperationAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class StudentsController : ControllerBase
    {
        private static readonly List<Students> students = new()
        {
            new Students
            {
                Id = 1,
                Name = "Capt. Peter",
                Age = 24,
                Address = "London"
            },
            new Students
            {
                Id = 2,
                Name = "Capt. Scott",
                Age = 24,
                Address = "Leeds"
            }
        };

        [HttpGet]
        public ActionResult<List<Students>> GetAllStudents()
        {
            return Ok(students);
        }

        [HttpGet("{id}")]
        public ActionResult<Students> GetStudentById(int id)
        {
            var student = students.FirstOrDefault(s => s.Id == id);

            if (student == null)
            {
                return NotFound();
            }

            return Ok(student);
        }

        [HttpPost]
        public ActionResult<Students> CreateStudent([FromBody] Students student)
        {
            student.Id = students.Count == 0
                ? 1
                : students.Max(s => s.Id) + 1;

            students.Add(student);

            return CreatedAtAction(
                nameof(GetStudentById),
                new { id = student.Id },
                student);
        }

        [HttpPut("{id}")]
        public ActionResult UpdateStudent(
            int id,
            [FromBody] Students updatedStudent)
        {
            var student = students.FirstOrDefault(s => s.Id == id);

            if (student == null)
            {
                return NotFound();
            }

            student.Name = updatedStudent.Name;
            student.Age = updatedStudent.Age;
            student.Address = updatedStudent.Address;

            return NoContent();
        }

        [HttpDelete("{id}")]
        public ActionResult DeleteStudent(int id)
        {
            var student = students.FirstOrDefault(s => s.Id == id);

            if (student == null)
            {
                return NotFound();
            }

            students.Remove(student);

            return NoContent();
        }
    }
}


The controller uses a static List<Students> as temporary storage. This means the data exists only while the application is running.

Step 5: Understand the CRUD Endpoints

The controller exposes five HTTP endpoints.

HTTP Method

Endpoint

Operation

GET

/api/students

Get all students

GET

/api/students/{id}

Get a student by ID

POST

/api/students

Create a student

PUT

/api/students/{id}

Update a student

DELETE

/api/students/{id}

Delete a student

These endpoints represent the standard CRUD workflow.

Step 6: Test the Read Operation
Run the application using F5 or the Start button in Visual Studio. If Swagger is enabled, the application will open the Swagger interface.

Expand:
GET /api/Students

Click Try it out, followed by Execute.

The response will contain the existing students:
[
  {
    "id": 1,
    "name": "Capt. Tim",
    "age": 24,
    "address": "Liverpool"
  },
  {
    "id": 2,
    "name": "Capt. Scott",
    "age": 24,
    "address": "Leeds"
  }
]

This demonstrates the Read operation.

Step 7: Get a Student by ID

To retrieve a specific student, use:
GET /api/Students/1

The API searches the collection for a matching ID.
var student = students.FirstOrDefault(s => s.Id == id);

if (student == null)
{
    return NotFound();
}

return Ok(student);


For ID 1, the response is:
{
  "id": 1,
  "name": "Capt. Tim",
  "age": 24,
  "address": "Liverpool"
}


If the requested student does not exist, the API returns an HTTP 404 Not Found response.

Step 8: Create a New Student
To create a student, use:
POST /api/Students

Send the following JSON request body:
{
  "name": "David",
  "age": 22,
  "address": "London"
}


The controller assigns a new ID and adds the student to the collection.
student.Id = students.Count == 0
    ? 1
    : students.Max(s => s.Id) + 1;

students.Add(student);


The API returns 201 Created along with the newly created resource.

Example response:
{
  "id": 3,
  "name": "David",
  "age": 22,
  "address": "London"
}

This demonstrates the Create operation.

Step 9: Update a Student

To update an existing student, use:
PUT /api/Students/3

Send the updated data:
{
  "name": "Peter",
  "age": 23,
  "address": "London"
}

The controller finds the student and updates its properties.
student.Name = updatedStudent.Name;
student.Age = updatedStudent.Age;
student.Address = updatedStudent.Address;

If the operation succeeds, the API returns:
204 No Content

This demonstrates the Update operation.

Step 10: Delete a Student

To delete a student, use:
DELETE /api/Students/3

The controller finds the student and removes it from the collection.
students.Remove(student);

If the deletion succeeds, the API returns:
204 No Content

If the student does not exist, the API returns:
404 Not Found

This demonstrates the Delete operation.

Step 11: Validate the CRUD Flow

The complete CRUD flow can now be tested as follows:
Create
  |
  v
POST /api/Students
  |
  v
Read
  |
  v
GET /api/Students
  |
  v
Update
  |
  v
PUT /api/Students/{id}
  |
  v
Read Updated Data
  |
  v
GET /api/Students/{id}
  |
  v
Delete
  |
  v
DELETE /api/Students/{id}


This provides a simple end-to-end test of the API.

Step 12: Customize the Controller

You may want to customize the controller logic according to your application's requirements.

For example, validation can be added before creating a student:
[HttpPost]
public ActionResult<Students> CreateStudent([FromBody] Students student)
{
    if (string.IsNullOrWhiteSpace(student.Name))
    {
        return BadRequest("Student name is required.");
    }

    if (student.Age <= 0)
    {
        return BadRequest("Age must be greater than zero.");
    }

    student.Id = students.Count == 0
        ? 1
        : students.Max(s => s.Id) + 1;

    students.Add(student);

    return CreatedAtAction(
        nameof(GetStudentById),
        new { id = student.Id },
        student);
}


This prevents invalid data from being added to the collection.

For a production application, validation would generally be implemented using model validation attributes or a dedicated validation approach rather than keeping all validation logic directly inside controller actions.
Step 13: Move from In-Memory Data to SQL Server

The example uses an in-memory list so that the CRUD concepts can be demonstrated without introducing database configuration.

For a real application, the data would normally be stored in a database such as SQL Server.

A common architecture would be:

Client
   |
   v
ASP.NET Core Controller
   |
   v
Service Layer
   |
   v
Repository / Data Access
   |
   v
SQL Server

Entity Framework Core can be used to connect the ASP.NET Core application to SQL Server.

For example, the required packages can be installed using the .NET CLI:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools


The exact package versions should match the .NET and Entity Framework Core versions used by the project.

Once a database is introduced, the static list can be replaced with an DbContext and database queries.

Why the Original Package Configuration Needs Attention?

The original implementation listed packages such as:
Microsoft.ASPNetCore
Microsoft.SqlServer
Microsoft.Data.SqlClient


These are not the appropriate set of packages for the MVC/API CRUD implementation shown in the article.

If SQL Server is being used with Entity Framework Core, the application should use the appropriate Entity Framework Core SQL Server provider, such as:
Microsoft.EntityFrameworkCore.SqlServer

Microsoft.Data.SqlClient is the SQL Server ADO.NET provider and is useful when directly working with SQL Server through ADO.NET, but it does not replace the Entity Framework Core SQL Server provider.
MVC Views vs Web API Controllers

There is an important distinction between the two approaches.

An ASP.NET Core MVC application commonly uses:
Controller
    |
    v
Razor Views
    |
    v
HTML UI

A Web API application commonly uses:
Client
    |
    v
API Controller
    |
    v
JSON Response


The supplied StudentsController uses:
[ApiController]
public class StudentsController : ControllerBase


Therefore, it is a Web API controller rather than an MVC controller that returns Razor Views.
If the goal is to create an MVC application with Create, Edit, Details, and Delete pages, the controller would instead work with Razor Views and a database context.

Common Mistakes to Avoid
Mixing MVC and Web API Terminology

An MVC controller and an API controller serve different purposes. Make sure the project template, controller base class, routes, and expected output match the application's architecture.

Assuming In-Memory Data Is Persistent
The static list is only temporary storage. Restarting the application resets the data.

Not Validating Input
APIs should validate incoming data before storing or processing it.

Exposing Internal Exception Details
Production APIs should avoid returning sensitive exception information directly to clients.

Using Manual ID Generation in Production
The example generates IDs from the current collection because it uses an in-memory list. A database should normally be responsible for generating unique primary keys.

Conclusion
CRUD operations are fundamental to most data-driven applications. ASP.NET Core provides a straightforward way to implement Create, Read, Update, and Delete operations through HTTP endpoints. In this example, we created a students model and implemented GET, POST, PUT, and DELETE operations using an ASP.NET Core Web API controller. We also tested the endpoints and reviewed how the same application can be extended with SQL Server and Entity Framework Core for persistent data storage.

The example is intentionally simple so that the CRUD workflow is easy to understand. In a production application, the next steps would typically include database persistence, model validation, authentication and authorization, service and repository layers, logging, error handling, and automated testing.



ASP.NET MVC Hosting - HostForLIFE.eu :: URL Creation Fundamentals In MVC

clock September 2, 2026 11:41 by author Peter

Let's start with MVC foundations. There are two ways to create a URL in the MVC framework: ActionLink and Raw HTML. In this tutorial, we will examine several methods of building URLs in MVC as well as other essential ideas of MVC.

Question - Which approach is best for URL creation?
Answer
Action LInk in the background queries the routing engine whenever the URL associated with the given controllers ACTION. Sometimes we do have Custom URLs associated with an action, and we require to change that URL in future. For this scenario actionLink will pick up the latest URL, you don't need to make any changes.

On the other hand, if you are using raw HTML, you need to update your links when URLs changed.

As a good programmer, we should always avoid changing URLs as URLs are the public contract of your app and can be referenced by other apps, and many times users bookmark the URLs. If you change them, all these bookmarks and references will be broken.

In the end, the decision is up to the programmer's choice, no hard and fast rule here.

Again, the simplest way is using raw HTML

1: Raw HTML
Example,
<a href = "Courses/Index"> View Course</a>

2: ActionLink
Below is the example of using ActionLink for URL creation.
@HTML.ActionLink("View Courses","Index","Courses")

If the targeted action needs a parameter we can make use of an anonymous object to pass the parameter values.
@HTML.ActionLink("View Courses","Index","Courses", new {id = 1})

This will generate a link as - courses/index/1

This method doesn't generate the link for a reason, we need to pass another argument to ActionLink. This argument can be null or an anonymous object to render any additional HTML attribute.
@HTML.ActionLink("View Courses","Index","Courses", new {id = 1}, null)

Type Helper Method
ViewResult View()
PartialViewResult PartialView()
RedirectResult Redirect()
ContentResult Content()
JsonResult Json()
RedirectToRouteResult RedirectToAction()
FileResult File()
HttpNotFoundResult HttpNotFound()
EmptyResult  

Passing Data to views in MVC
We should avoid passing data using ViewData and ViewBag as these methods are fragile and need a lot of casting which makes code ugly. Instead, we can pass model or viewModel directly to view.
return View(Course);

Razor Views
@if(condition)
{
    // c# or HTML code
}

@foreach(...)
{
}

We can render a class or any attribute conditionally as follows,
@{
    var className=Model.Movies.Count >3 ? "Popular" : null;
}
<h2 class = "@className">...</h2>


Partial View
@Html.Partial("_NavBar")

Types of Routing in MVC
1. Convention based Routing
Here we can specify the routing in RouteConfig.cs file and mention the Controller, action which needs to be invoked using mapRoute method of routes collection.

2. Attribute based Routing
Here we can apply route by decorating the action method with the Route keyword followed by the path.

Authentication in MVC
Use [authorize] keyword. Apply it to action, controller or globally (in FilterConfig.cs)
Enabling Social Login in MVC

Step 1
Enable SSL: Select project, press F4, set SSL enabled to true.

Step 2

Copy SSL URL, select the project, go to properties, in the Web tab, set startup URL.

Step 3
Apply RequireSSL filter globally in FilterConfig.cs file.

Step 4

Register your app with external authentication providers to get secret key/secret. In AppStart.cs/Startup.Auth.cs, add corresponding providers and your key/secret.

Summary
In this article, we explored different ways of URL creation in MVC and different fundamental concepts of MVC. I hope you liked the article. Until Next Time - Happy Learning.



ASP.NET MVC Hosting - HostForLIFE.eu :: Areas in ASP.NET MVC

clock August 28, 2026 13:51 by author Peter

The Model, View, and Controller folders are automatically generated when we start a new MVC project.

This structure is typical for small applications, however the single Model, View, and Controller may get cumbersome as your program expands and becomes more sophisticated. so that we may use regions to manage a complicated MVC application. We can build more maintainable code for an application that is neatly divided into modules by using areas.

Thus, start by creating a new, empty MVC project.

Next, choose the region by performing a right-click on Solution Explorer and selecting Add.

Provide a name.

Now add a second Employee area. In your Solution Explorer show your Model, View and Controller in a different student and employee area.

Now add a Home Controller and in the Index action add an Index View for both the student and employee area.

Now run the project. (Ctrl+F5).

For the Teacher area the follwing is the URL localhost/Teachers/Home/Index.

Here Teachers is the area name, Home is the controller and Index is the Action name.

For the Teacher area the follwing is the URL localhost/Students/Home/Index. Here Students is the area name, Home is the controller and Index is the Action name.



ASP.NET MVC Hosting - HostForLIFE.eu :: URL Routing Of ASP.NET MVC And ASP.NET Web Forms

clock August 18, 2026 13:47 by author Peter

Important Points Regarding ASP.NET MVC
The program ASP.NET MVC is open-source. The ASP.NET MVC is a web application framework developed by Microsoft, which implements the model–view–controller pattern. Partial Views in ASP.NET MVC allow for code reuse. Views and logic are stored independently in ASP.NET MVC. Razor is the default syntax used by ASP.NET MVC.HTML aids are available in ASP.NET MVC.ASP.NET MVC adheres to the MVC (approach, View, Controller) pattern-based development approach and is lightweight. View state is not supported by ASP.NET MVC.



Key Notes To ASP.NET Web Form
ASP.NET Web Form is not Open Source.ASP.NET Web Form follows a traditional event-driven development model.ASP.NET Web Form has server controls.ASP.NET Web Form supports view state for state management at client side.ASP.NET Web Form follows Web Forms Syntax.In ASP.NET Web Form, Web Forms(ASPX) i.e. views are tightly coupled to Code behind(ASPX.CS) i.e. logic. ASP.NET Web Form has User Controls for code re-usability.

Url Path Note Of ASP.NET MVC
ASP.NET MVC has route-based URLs which means URLs are divided into controllers and actions and moreover it is based on controller not on physical files.

Url Path Note Of ASP.NET Web Form
ASP.NET Web Form has file-based URLs means file name exist in the URLs must have its physical existence.

Description
Here I built one ASP.NET MVC and ASP.NET web form application.That will show you what the URL Path Concept Between ASP.NET MVC and ASP.NET Web Forms.
 
Steps to be followed For ASP.NET MVC

Step 1
Create a Mvc Project named "MvcWeb".

Step 2
Create class file in Models Folder named "Student.cs".

Code Ref
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.ComponentModel.DataAnnotations;  
      
    namespace MvcWeb.Models  
    {  
        public class Student  
        {  
            [Display(Name = "Name")]  
            public string StudentName { get; set; }  
        }  
    } 

Code Description
Add one variable or entity named "StudentName". To display the result in the page associate with label htmlhelper.
public string StudentName { get; set; } 

We can control the display of data in a view using display attributes that are found in System.ComponentModel.DataAnnotations namespace.
    [Display(Name = "Name")]  

Step 3

Create a controller class file named "HomeController.cs".

Code Ref
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Web.Mvc;  
    using MvcWeb.Models;  
      
    namespace MvcWeb.Controllers  
    {  
        public class HomeController : Controller  
        {  
            //  
            // GET: /Home/  
      
            public ActionResult HFL()  
            {  
                return View();  
            }  
      
        }  
    } 

Code Description
Here I created one controller action method named "HFL()". Add the namespace reference on Model class that is,
    using MvcWeb.Models;  

Step 4
Create one view named "HFL.cshtml" in Views/Home Folder as the same name in controller action method.

Code Ref
    @model MvcWeb.Models.Student  
    @{  
        ViewBag.Title = "Satyaprakash";  
    }  
    <h2 style="background-color: Yellow; color: Blue; text-align: center; font-style: oblique">  
        Satyaprakash's Mvc Path Concept</h2>  
    <fieldset>  
        <legend style="font-family: Arial Black; color: blue">Student Name</legend>  
        @Html.LabelFor(m => m.StudentName, "Satyaprakash Samantaray")  
    </fieldset>  
      
      
    <footer>    
          <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@    
    </footer> 


Code Description
Here I added namespace in view to access properties of student model class file. 
    @model MvcWeb.Models.Student 

LabelFor helper method is a strongly typed extension method. It generates a html label element for the model object property specified using a lambda expression. LabelFor() method Signature: MvcHtmlString LabelFor(<Expression<Func<TModel,TValue>> expression) .
    @Html.LabelFor(m => m.StudentName, "Peter") 

We have specified the StudentName property of Student model using lambda expression in the LabelFor() method. So, it generates <label> and sets label text to the same as StudentName property name. Here labelfor htmlhelper will show the name "Satyaprakash Samantaray". 
 
Step 5
Set as start page In mvc.

Go to this file path "MvcWeb\App_Start\RouteConfig.cs". Open the file called "RouteConfig.cs".

Code Ref
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Web.Mvc;  
    using System.Web.Routing;  
      
    namespace MvcWeb  
    {  
        public class RouteConfig  
        {  
            public static void RegisterRoutes(RouteCollection routes)  
            {  
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
      
                routes.MapRoute(  
                    name: "Default",  
                    url: "{controller}/{action}/{id}",  
                    defaults: new { controller = "Home", action = "HFL", id = UrlParameter.Optional }  
                );  
            }  
        }  
    } 


Code Description
So here I set start page :
    defaults: new { controller = "Home", action = "HFL", id = UrlParameter.Optional } 

 At page load time the controller Home and action method name HFL of home controller will be loaded.

OUTPUT OF MVC URL
http://localhost:1064/home/HFL

Steps to be followed For ASP.NET Webform

Step1
Create a ASP.NET Webform Project named "AspxWeb".

Step2
Create a new folder named "Home".

Step3
Then add webform named "HFL.aspx".

Code ref of HFL.aspx
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HFL.aspx.cs" Inherits="AspxWeb.Home.HFL" %>  
      
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
    <html xmlns="http://www.w3.org/1999/xhtml">  
    <head runat="server">  
        <title>Satyaprakash</title>  
    </head>  
    <body>  
        <form id="form1" runat="server">  
        <div>  
            <h2 style="background-color: Yellow; color: Blue; text-align: center; font-style: oblique">  
                Peter's Webform Path Concept</h2>  
            <fieldset>  
                <legend style="font-family: Arial Black; color: blue">Student Name</legend>  
                <asp:Label ID="Peterlbl" runat="server" Text="Label"></asp:Label>  
            </fieldset>  
        </div>  
        </form>  
    </body>  
    <footer>      
            <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">©<script>document.write(new Date().toDateString()); </script></p>      
        </footer>  
    </html> 

Code Description
Here I added label server control named "Peterlbl" .
    <asp:Label ID="
Peterlbl" runat="server" Text="Label"></asp:Label> 

Code ref of HFL.aspx.cs
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Web.UI;  
    using System.Web.UI.WebControls;  
      
    namespace AspxWeb.Home  
    {  
        public partial class HFL : System.Web.UI.Page  
        {  
            protected void Page_Load(object sender, EventArgs e)  
            {  
                Satyalbl.Text = "Peter";  
            }  
        }  
    } 


Code Description

In the page_load() event I added label control id with associate result which will show in webpage during load time.

Step4
Set start page follow below image .

Here the Home is the name of the folder and HFL.aspx name of the webform inside the Home folder.

Notes
In MVC , URL is mapped to a controller action method. Where as in web forms application, the URL is mapped to a physical file.

Module Summary

  • What is ASP.NET MVC.
  • What is ASP.NET Webform.
  • The url path concept between ASP.NET MVC and ASP.NET Web Forms.
  • Set start page in ASP.NET MVC and ASP.NET Web Forms.


ASP.NET MVC Hosting - HostForLIFE.eu :: Consuming WCF Service in MVC Application Using Entity Framework

clock August 13, 2026 14:15 by author Peter

This article includes a step by step tutorial to learn WCF using MVC in Visual Studio. We are also using the Entity Framework (.edmx model) for database operations. This scenario targets the user of Entity Framework Model's first approach that consumes WCF service which is consumed in MVC applications for CRUD operations.

Note :
Make sure that Entity Framework is already installed with Visual Studio. Otherwise, install it using NuGet Packages.
Create a table in your database with the name of "UserDetail", as the following.

Step 1. Crate a blank solution
Open Visual Studio.
File - New - Project…
Select "Other project Type" in the left pane and choose "Blank Solution."
Type the name of the Solution "MvcWcfEF";

Step 2. Creating an WCF Application
Right click on the MvcWcfEF solution in Solution Explorer and go to Add  New Project.

Select WCF Service Application Library and type the name as WcfServiceApp.
Click on OK.

Step 3. Creating a service for CRUD operation
Right click on the WcfServiceApp project and select Add - New Item.
Choose Web option from left pane and select "WCF Service".
Type the name as "MyService.svc" and click on Add button.

Step 4. Creating an Entity Framework Model
Right click on the WcfServiceApp project and select Add - New Item.
Choose Data option from left pane and select "ADO.NET Entity data model".
Type the name as "EntityModel.edmx" and click on Add button, same as in the following images.

 

Select your database and type the name of connection settings in web.config as "TestDBEntities".

Step 5. Write a service for CRUD operation
Open MyService.csv page from WcfService application and write the following code:
        using System;  
        using System.Collections.Generic;  
        using System.Data;  
        using System.Linq;  
        using System.Runtime.Serialization;  
        using System.ServiceModel;  
        using System.Text;  
          
        namespace WcfServiceApp  
        {  
            // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "MyService" in code, svc and config file together.  
            // NOTE: In order to launch WCF Test Client for testing this service, please select MyService.svc or MyService.svc.cs at the Solution Explorer and start debugging.  
            public class MyService : IMyService  
            {  
                public void DoWork()  
                {  
                }  
          
                public List<UserDetail> GetAllUser()  
                {  
                    List<UserDetail> userlst = new List<UserDetail>();  
                    TestDBEntities tstDb = new TestDBEntities();  
                    var lstUsr = from k in tstDb.UserDetails select k;  
                    foreach (var item in lstUsr)  
                    {  
                        UserDetail usr = new UserDetail();  
                        usr.Id = item.Id;  
                        usr.Name = item.Name;  
                        usr.Email = item.Email;  
                        userlst.Add(usr);  
          
                    }  
          
                    return userlst;  
                }  
          
          
          
                public UserDetail GetAllUserById(int id)  
                {  
          
                    TestDBEntities tstDb = new TestDBEntities();  
                    var lstUsr = from k in tstDb.UserDetails where k.Id==id select k;  
                    UserDetail usr = new UserDetail();  
                    foreach (var item in lstUsr)  
                    {  
          
                        usr.Id = item.Id;  
                        usr.Name = item.Name;  
                        usr.Email = item.Email;  
          
          
                    }  
          
                    return usr;  
                }  
          
                public int DeleteUserById(int Id)  
                {  
          
                    TestDBEntities tstDb = new TestDBEntities();  
                    UserDetail usrdtl = new UserDetail();  
                    usrdtl.Id = Id;  
                    tstDb.Entry(usrdtl).State = EntityState.Deleted;  
                    int Retval = tstDb.SaveChanges();  
                    return Retval;  
                }  
          
                public int AddUser(string Name, string Email)  
                {  
                    TestDBEntities tstDb = new TestDBEntities();  
                    UserDetail usrdtl = new UserDetail();  
                    usrdtl.Name = Name;  
                    usrdtl.Email = Email;  
                    tstDb.UserDetails.Add(usrdtl);  
                    int Retval = tstDb.SaveChanges();  
                    return Retval;  
                }  
              public int UpdateUser(int Id,string Name, string Email)  
                {  
                    TestDBEntities tstDb = new TestDBEntities();  
                    UserDetail usrdtl = new UserDetail();  
                    usrdtl.Id = Id;  
                    usrdtl.Name = Name;  
                    usrdtl.Email = Email;  
                    tstDb.Entry(usrdtl).State = EntityState.Modified;  
                     
                    int Retval = tstDb.SaveChanges();  
                    return Retval;  
                }  
                 
            }  
        }  


Now, Open IMyService and write the "ServiceContract" and "DatatContract", as follows.
using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Runtime.Serialization;  
    using System.ServiceModel;  
    using System.Text;  
      
    namespace WcfServiceApp  
    {  
        // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IMyService" in both code and config file together.  
        [ServiceContract]  
        public interface IMyService  
        {  
            [OperationContract]  
           List<UserDetail> GetAllUser();  
            [OperationContract]  
            int AddUser(string Name, string Email);  
            [OperationContract]  
            UserDetail GetAllUserById(int id);  
      
            [OperationContract]  
            int UpdateUser(int Id, string Name, string Email);  
      
            [OperationContract]  
            int DeleteUserById(int Id);  
        }  
      
      
        [DataContract]  
        public class UserDetails  
        {  
            [DataMember]  
            public int Id { get; set; }  
            [DataMember]  
            public string Name { get; set; }  
            [DataMember]  
            public string Email { get; set; }  
          
          
        }  
    }  

Service has been completed. Now, build the service.

  • Press F5 to run the Service.
  • Copy the Service URL, as shown in following image (localhost:1034/MyService.svc), for creating the reference.

Step 6. Creating an MVC Application

  • Now, right click on the "MvcWcfEF " solution in Solution Explorer, again.
  • Select e New  Project…
  • Select ASP.NET MVC3/4 Web Application.
  • Enter the name of application as "MvcApp".
  • Click on OK.

Adding a Project Priority and setting the reference

  • Right click on the MvcApp and click on add service reference as in he image below.
  • Paste the Copied Service URL in the given address and press Go button.
  • All the services will display, as in the folowing picture. Just give the Namespace as "ServiceRefernce1" and click on OK button.

Since WCF service application and MVC application both are in the same solution, we have to build the Service first and then the MVC application in order to consume the service in MVC application. Do the following for that,
Right Click on the MvcWcfEF Solution in Solution Explorer and click on properties.
Check the "Multiple Startup Project " and set the application priority for WCF and MVC application (WCF service should be first and MVC afterwards), as in the following image.

Create a Model

Right click on Model folder and click on Class. Write the class name as "User" and create the following properties.

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
      
    namespace MvcApp.Models  
    {  
        public class User  
        {  
      
             
                public int Id { get; set; }  
                 
                public string Name { get; set; }  
                 
                public string Email { get; set; }  
      
        }  
    }  

Create a Controller

Right click on the Controller folder and click on add controller. Give the name of controller as "HomeController" and write the following action for CRUD operation.
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Web.Mvc;  
    using MvcApp.Models;  
      
      
    namespace MvcApp.Controllers  
    {  
        public class HomeController : Controller  
        {  
            //  
            // GET: /Home/  
            ServiceReference1.MyServiceClient ur = new ServiceReference1.MyServiceClient();  
            public ActionResult Index()  
            {  
                List<User> lstRecord = new List<User>();  
                 
                var lst = ur.GetAllUser();  
      
                foreach (var item in lst)  
                {  
                    User usr = new User();  
                    usr.Id = item.Id;  
                    usr.Name = item.Name;  
                    usr.Email = item.Email;  
                    lstRecord.Add(usr);  
                  
                }  
      
      
                return View(lstRecord);  
            }  
      
      
            public ActionResult Add()  
            {  
      
                return View();  
            }  
            [HttpPost]  
            public ActionResult Add(User mdl)  
            {  
      
                User usr= new User();  
                usr.Name=mdl.Name;  
                usr.Email=mdl.Email;  
                ur.AddUser(usr.Name,usr.Email);  
                return RedirectToAction("Index", "Home");  
                
            }  
            public ActionResult Delete(int id)  
            {  
                int retval = ur.DeleteUserById(id);  
                if (retval > 0)  
                {  
                    return RedirectToAction("Index", "Home");  
                }  
      
                return View();  
            }  
      
            public ActionResult Edit(int id)  
             {  
                var lst = ur.GetAllUserById(id);  
                  User usr = new User();  
                  usr.Id = lst.Id;  
                  usr.Name = lst.Name;  
                  usr.Email = lst.Email;  
                  return View(usr);  
      
            }  
            [HttpPost]  
            public ActionResult Edit(User mdl)  
            {  
                User usr = new User();  
                usr.Id = mdl.Id;  
                usr.Name = mdl.Name;  
                usr.Email = mdl.Email;  
      
      
                int Retval = ur.UpdateUser(usr.Id, usr.Name, usr.Email);  
                if (Retval > 0)  
                {  
                    return RedirectToAction("Index", "Home");  
                }  
                return View();  
            }  
        }  
    }  

Creating a View
Creating a view is very simple. Just right click on All action of the controller and click on Add View. The following is the code for all views (Index, Add, Edit). 
Index.cshtml
    @model IEnumerable<MvcApp.Models.User>  
      
    @{  
        ViewBag.Title = "Index";  
    }  
      
      
    @using (Html.BeginForm()){  
        <div>  
            <h2>User Details</h2>  
             @Html.ActionLink("Add User", "Add", "")  
        </div>  
        <div>  
             <table >  
                <tr style="background-color: #FFFACD; text-align:center">  
                    <th style="text-align:left">  
                        Name  
                    </th>  
                    <th style="text-align:left">  
                       Email  
                    </th>  
                    <th style="text-align:left">  
                        Manage  
                    </th>  
                </tr>  
      
                @{  
                    foreach (var item in Model)  
                    {  
                    <tr style="background-color: #FFFFF0">  
                        <td>  
                            @item.Name  
                        </td>  
                        <td>  
                            @item.Email  
                        </td>  
                         
                        <td>  
                            @Html.ActionLink("Edit", "Edit", new { id = @item.Id }) /@Html.ActionLink("Delete", "Delete", new {[email protected] })   
                             
                        </td>  
                         
                    </tr>  
                    }  
                }  
      
            </table>  
      
        </div>  
         
      
    }  


Add.cshtml
    @model MvcApp.Models.User  
      
    @{  
        ViewBag.Title = "Add";  
    }  
      
    <h2>Add New User</h2>  
      
    @using (Html.BeginForm()) {   
      
    <div style="text-align:center">  
      
        <table>  
            <tr>  
                <td>  
                    Name :   
                </td>  
                <td>   
                    @Html.TextBoxFor(m=>m.Name)  
                </td>  
            </tr>  
      
             <tr>  
                <td>  
                    Email :   
                </td>  
                <td>   
                    @Html.TextBoxFor(m=>m.Email)  
                </td>  
            </tr>  
             <tr>  
                <td>  
                    Email :   
                </td>  
                <td>   
                   <input type="submit" value="Submit" />  
                </td>  
            </tr>  
        </table>  
      
    </div>    
    }  


Edit.cshtml
    @model MvcApp.Models.User  
      
    @{  
        ViewBag.Title = "Edit";  
    }  
      
    <h2>Edit User</h2>  
      
    @using (Html.BeginForm()) {   
      
    <div style="text-align:center">  
      
        <table>  
            <tr>  
                <td>  
                    Name :   
                </td>  
                <td>   
                    @Html.TextBoxFor(m=>m.Name)  
                </td>  
            </tr>  
      
             <tr>  
                <td>  
                    Email :   
                </td>  
                <td>   
                    @Html.TextBoxFor(m=>m.Email)  
                </td>  
            </tr>  
             <tr>  
                <td>  
                       
                </td>  
                <td>   
                   <input type="submit" value="Update" />  
                </td>  
            </tr>  
        </table>  
      
    </div>  
    }  

Now, press F5 to run the Application



ASP.NET MVC Hosting - HostForLIFE.eu :: Different Ways Of Rendering Partial View In MVC

clock August 5, 2026 13:52 by author Peter

There are 5 different way of rendering a partial view.

  • Partial
  • Render partial
  • Action
  • Render action
  • JQuery load function

When to use a partial view?

  • To break up large markup files into smaller components.
  • To reduce the duplication of common markup content across markup files.
  • Partial views shouldn't be used to maintain common layout elements. Common layout elements should be specified in the _Layout.cshtml files.

Difference between RenderPartial and Partial
Partial
The partial method returns an MvcHtmlString object. Basically, it stringifies the HTML content in the location where it was specified.

RenderPartial
The RenderPartial method will not actually return any values or strings and instead, it will write the Partial View that is requested to the Response Stream through response.write internally.
 
Difference between RenderAction and Action
RenderAction

The RenderAction method renders the result directly to the response which means it is more efficient if the action returns a large amount of HTML.

Action
Action method returns a string with the result.
 
Let's see this via an example. 

Step 1
Open Visual Studio 2015 or an IDE of your choice and create a new project.

Step 2
Choose web application project and give an appropriate name to your project.

Step 3
Select empty template, check on MVC checkbox below, and click OK.

Step 4
Right click on the Models folder and add a database model. Add Entity Framework now. For that, right-click on Models folder, select Add, then select "New Item".

You will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name EmployeeModel (this name is not mandatory, you can give any name) and click "Add".

After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click "Next".

After clicking on "Next", a window will appear. Choose "New Connection". Another window will appear. Add your server name - if it is local, then enter dot (.). Choose your database and click "OK".

The connection will be added. If you wish, save the connection name as you want. You can change the name of your connection below. It will save the connection in the web config. Now, click "Next"

After clicking on NEXT, another window will appear. Choose the database table name as shown in the below screenshot and click "Finish".


Entity Framework gets added and the respective class gets generated under the Models folder.

Step 5
Right click on controllers folder add a controller.

A window will appear. Choose MVC5 Controller-Empty and click "Add".

After clicking on "Add", another window will appear with DefaultController. Change the name to HomeController and click "Add". The HomeController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of Default, just change Home;

Complete code for Home Controller
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Web.Mvc;  
    using MvcPartialView_Demo.Models;  
       
    namespace MvcPartialView_Demo.Controllers  
    {  
        public class HomeController : Controller  
        {  
            private readonly EmployeeContext _dbContext=new EmployeeContext();  
       
            public ActionResult Index()  
            {  
                var employee = _dbContext.Employees.ToList();  
                return View(employee);  
            }  
       
            public PartialViewResult Employee()  
            {  
                return PartialView("_employee");  
            }  
        }  
    }  

Step 6

Right-click on Index method in HomeController. The "Add View" window will appear with default index name checked (use a Layout page), and click on "Add.


Html.Partial
    @{  
        ViewBag.Title = "Index";  
    }  
       
    <h3>List of Employee</h3>  
    @Html.Partial("_employee")  


Html.RenderPartial
    @{  
        ViewBag.Title = "Index";  
    }  
       
    <h3>List of Employee</h3>  
    @{  
        Html.RenderPartial("_employee");  
    }  


Html.Action
    @{  
        ViewBag.Title = "Index";  
    }  
       
    <h3>List of Employee</h3>  
    @{  
        @Html.Action("Employee")  
    }  

Html.RenderAction
    @{  
        ViewBag.Title = "Index";  
    }  
       
    <h3>List of Employee</h3>  
    @{  
        Html.RenderAction("Employee");  
    }  


JQuery load function 
    @{  
        ViewBag.Title = "Index";  
    }  
    <script src="~/Scripts/jquery-3.3.1.min.js"></script>  
    <h3>List of employee</h3>  
    <div id="partialView">  
    </div>  
    <script type="text/javascript">  
        $(document).ready(function() {  
            $("#partialView").load('@Url.Content("/Home/Employee")');  
        });  
    </script>  

Step 7
Right-click on the "Shared" folder index views folder add a view name it _employee checked on create as a partial view, and click on "Add".

Code for partial view
    @model IEnumerable<MvcPartialView_Demo.Models.Employee>  
       
    <table class="table table-bordered">  
        <thead>  
        <tr>  
            <th>@Html.DisplayNameFor(m=>m.Name)</th>  
            <th>@Html.DisplayNameFor(m=>m.Gender)</th>  
            <th>@Html.DisplayNameFor(m=>m.Age)</th>  
            <th>@Html.DisplayNameFor(m=>m.Position)</th>  
            <th>@Html.DisplayNameFor(m=>m.Office)</th>  
            <th>@Html.DisplayNameFor(m=>m.HireDate)</th>  
            <th>@Html.DisplayNameFor(m=>m.Salary)</th>  
        </tr>  
        </thead>  
        <tbody>  
        @foreach (var emp in Model)  
        {  
            <tr>  
                <td>@emp.Name</td>  
                <td>@emp.Gender</td>  
                <td>@emp.Age</td>  
                <td>@emp.Position</td>  
                <td>@emp.Office</td>  
                <td>  
                    @if (emp.HireDate != null)  
                    {  
                        @emp.HireDate.Value.ToString("dd/MM/yyyy")  
                    }  
                </td>  
                <td>@emp.Salary</td>  
            </tr>  
        }  
        </tbody>  
    </table>  

Step 8
Build and run your project by pressing CTRL+F5.



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.


Month List

Tag cloud

Sign in