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 :: FileResult In ASP.NET Core MVC

clock May 13, 2020 09:18 by author Peter

This article is an overview of FileResult in ASP.Net Core MVC. The FileResult actions are used to read and write files. FileResult is the parent of all file-related action results. There is a method on ControllerBase class called File. This method accepts a set of parameters based on the type of file and its location, which maps directly to the more specific return types. I’ll discuss how to use all the FileResult actions available in ASP.Net Core MVC.

There are different type of file results in core MVC.
FileResult
FileContentResult
FileStreamResult
VirtualFileResult
PhysicalFileResult

FileResult

FileResult is the parent of all file-related action results. It is a base class that is used to send binary file content to the response. It represents an ActionResult that when executed will write a file as the response.

public FileResult DownloadFile() 

     return File("/Files/File Result.pdf", "text/plain", "File Result.pdf"); 


FileContentResult
FileContentResult is an ActionResult that when executed will write a binary file to the response.
public FileContentResult DownloadContent() 

            var myfile = System.IO.File.ReadAllBytes("wwwroot/Files/FileContentResult.pdf"); 
            return new FileContentResult(myfile, "application/pdf"); 


FileStreamResult

FileStreamResult Sends binary content to the response by using a Stream instance when we want to return the file as a FileStream.
public FileStreamResult CreateFile() 

   var stream = new MemoryStream(Encoding.ASCII.GetBytes("Hello World")); 
   return new FileStreamResult(stream, new MediaTypeHeaderValue("text/plain")) 
   { 
      FileDownloadName = "test.txt" 
   }; 


VirtualFileResult
A FileResult that on execution writes the file specified using a virtual path to the response using mechanisms provided by the host. You can use VirtualFileResult if you want to read a file from a virtual address and return it.
public VirtualFileResult VirtualFileResult() 

    return new VirtualFileResult("/Files/PhysicalFileResult.pdf", "application/pdf"); 


PhysicalFileResult
A FileResult on execution will write a file from disk to the response using mechanisms provided by the host.You can use PhysicalFileResult to read a file from a physical address and return it, as shown in PhysicalFileResult method.
public PhysicalFileResult PhysicalFileResult() 

   return new PhysicalFileResult(_environment.ContentRootPath + "/wwwroot/Files/PhysicalFileResult.pdf", "application/pdf"); 


Step 1
Open Visual Studio 2019 and select the ASP.NET Core Web Application template and click Next.

Step 2
Name the project FileResultActionsCoreMvc_Demo and click Create.

Step 3
Select Web Application (Model-View-Controller), and then select Create. Visual Studio used the default template for the MVC project you just created.

Step 4
In Solution Explorer, right-click the wwwroot folder. Select Add > New Folder. Name the folder Files. Add some files to work with them.

Complete controller code
using Microsoft.AspNetCore.Hosting; 
using Microsoft.AspNetCore.Mvc; 
using Microsoft.Net.Http.Headers; 
using System.IO; 
using System.Text; 
 
namespace FileResultActionsCoreMvc_Demo.Controllers 

    public class HomeController : Controller 
    { 
        private readonly IWebHostEnvironment _environment; 
 
        public HomeController(IWebHostEnvironment environment) 
        { 
            _environment = environment; 
        } 
        public IActionResult Index() 
        { 
            return View(); 
        } 
 
        public FileResult DownloadFile() 
        { 
            return File("/Files/File Result.pdf", "text/plain", "File Result.pdf"); 
        } 
 
        public FileContentResult DownloadContent() 
        { 
            var myfile = System.IO.File.ReadAllBytes("wwwroot/Files/FileContentResult.pdf"); 
            return new FileContentResult(myfile, "application/pdf"); 
        } 
 
        public FileStreamResult CreateFile() 
        { 
            var stream = new MemoryStream(Encoding.ASCII.GetBytes("Hello World")); 
            return new FileStreamResult(stream, new MediaTypeHeaderValue("text/plain")) 
            { 
                FileDownloadName = "test.txt" 
            }; 
        } 
        public VirtualFileResult VirtualFileResult() 
        { 
            return new VirtualFileResult("/Files/PhysicalFileResult.pdf", "application/pdf"); 
        } 
 
        public PhysicalFileResult PhysicalFileResult() 
        { 
            return new PhysicalFileResult(_environment.ContentRootPath + "/wwwroot/Files/PhysicalFileResult.pdf", "application/pdf"); 
        } 
 
    } 


Step 5
Open Index view which is in views folder under Home folder. Add the below code in Index view.
Index View
@{ 
    ViewData["Title"] = "Home Page"; 

 
<h3 class="text-center text-uppercase">FileResult Action in core mvc</h3> 
<ul class="list-group list-group-horizontal"> 
    <li class="list-group-item"><a asp-action="DownloadFile" asp-controller="Home">File Result</a></li> 
    <li class="list-group-item"><a asp-action="DownloadContent" asp-controller="Home" target="_blank">File Content Result</a></li> 
    <li class="list-group-item"><a asp-action="CreateFile" asp-controller="Home">File Stream Result</a></li> 
    <li class="list-group-item"><a asp-action="VirtualFileResult" asp-controller="Home" target="_blank">Virtual File Result</a></li> 
    <li class="list-group-item"><a asp-action="PhysicalFileResult" asp-controller="Home" target="_blank">Physical File Result</a></li> 
</ul> 


Step 6
Build and run your Project ctrl+F5



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

clock April 9, 2020 05:10 by author Peter

What is an Html Helper?
Html helper is a method that is used to render HTML content in a view. Html helpers are implemented using an extension method. If you want to create an input text box with

id=email and name in email:
  <input type=text id=email name=email value=’’/> 


This is all the Html we need to write -- by using the helper method it becomes so easy:
  @Html.TextBox(‘email’) 

It will generate a textbox control whose name is the email.

If we want to assign the value of the textbox with some initial value then use the below method:
  @Html.TextBox(‘email’,’[email protected]’) 

If I want to set an initial style for textbox we can achieve this by using the below way:
  @Html.TextBox(‘email’,’[email protected]’,new {style=’your style here’ , title=’your title here’});  

Here the style we pass is an anonymous type.

If we have a reserved keyword like class readonly and we want to use this as an attribute  we will do this using the below method, which means append with @ symbol with the reserved word.
  @Html.TextBox(‘email’,’[email protected]’,new {@class=’class name’, @readonly=true}); 

If we want to generate label:
  @Html.Label(‘firstname’,’sagar’) 

For password use the below Html helper method to create password box:
  @Html.Password(“password”) 

If I want to generate a textarea then for this also we have a method:
  @Html.TextArea(“comments”,”,4,12,null)  

In the above code 4 is the number of rows and 12 is the number of columns.

To generate a hidden box:
  @Html.Hidden(“EmpID”) 

Hidden textboxes are not displayed on the web page but used for storing data and when we need to pass data to action method then we can use that.

Is it possible to create our Html helpers in asp.net MVC?

Yes, we can create our Html helpers in MVC.

Is it mandatory to use Html helpers?

No, we can use plain Html for that but Html helpers reduce a significant amount of Html code to write that view.
Also, your code is simple and maintainable and if you require some complicated logic to generate view then this is also possible.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Partial View in MVC

clock March 20, 2020 12:00 by author Peter

Partial view in ASP.NET MVC is special view which renders a portion of view content. It is just like a user control of a web form application. Partial can be reusable in multiple views. It helps us to reduce code duplication. In other word a partial view enables us to render a view within the parent view.
 

The partial view is instantiated with its own copy of a ViewDataDictionary object which is available with the parent view so that partial view can access the data of the parent view. If we made the change in this data (ViewDataDictionary object), the parent view's data is not affected. Generally the Partial rendering method of the view is used when related data that we want to render in a partial view is part of our model.
 
Creating Partial View
To create a partial view, right-click on view -> shared folder and select Add -> View option. In this way we can add a partial view.
 

Creating Partial View
It is not mandatory to create a partial view in a shared folder but a partial view is mostly used as a reusable component, it is a good practice to put it in the "shared" folder.

HTML helper has two methods for rendering the partial view: Partial and RenderPartial.
    <div> 
        @Html.Partial("PartialViewExample") 
    </div> 
    <div> 
        @{ 
            Html.RenderPartial("PartialViewExample"); 
        } 
    </div>

@Html.RenderPartial
The result of the RenderPartial method is written directly into the HTTP response, it means that this method used the same TextWriter object as used by the current view. This method returns nothing.
 
@Html.Partial
This method renders the view as an HTML-encoded string. We can store the method result in a string variable.
 
The Html.RenderPartial method writes output directly to the HTTP response stream so it is slightly faster than the Html.Partial method.
 
Returning a Partial view from the Controller's Action method:
    public ActionResult PartialViewExample() 
    { 
        return PartialView(); 
    }

Render Partial View Using jQuery
Sometimes we need to load a partial view within a model popup at runtime, in this case we can render the partial view using JQuery element's load method.
    <script type="text/jscript"> 
            $('#partialView').load('/shared/PartialViewExample’); 
    </script>



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Modal Popup In MVC Application

clock February 28, 2020 11:15 by author Peter

In this post we will implement modal pop up to display the detailed information of user after clicking on detail anchor. So this is the view on which we are going to apply modal popup.

View code
Enumerable<CodeFirst.Models.FriendsInfo> 
 
@{ 
    ViewBag.Title = "Index"; 

 
<h2>Index</h2> 
 
<p> 
    @Html.ActionLink("View All", "Index") 
 
    @using (Html.BeginForm("Search", "Home", FormMethod.Post)) 
    { 
        <table> 
            <tr> 
                <td> 
                    <input type="text" id="txtName" name="searchparam" placeholder="type here to search" /> 
                </td> 
                <td> 
                    <input type="submit" id="btnSubmit" value="Search" /> 
                </td> 
            </tr> 
        </table> 
    } 
 
</p> 
<table class="table"> 
    <tr> 
        <th> 
            @Html.DisplayNameFor(model => model.Name) 
        </th> 
        <th> 
            @Html.DisplayNameFor(model => model.Mobile) 
        </th> 
        <th> 
            @Html.DisplayNameFor(model => model.Address) 
        </th> 
        <th></th> 
    </tr> 
 
    @foreach (var item in Model) 
    { 
        <tr> 
            <td> 
                @Html.DisplayFor(modelItem => item.Name) 
            </td> 
            <td> 
                @Html.DisplayFor(modelItem => item.Mobile) 
            </td> 
            <td> 
                @Html.DisplayFor(modelItem => item.Address) 
            </td> 
            <td> 
                @*@Html.ActionLink("Edit", "Edit", new { id=item.Id }) | 
                    @Html.ActionLink("Details", "Details", new { id=item.Id }) | 
                    @Html.ActionLink("Delete", "Delete", new { id=item.Id })*@ 
 
                <a href="javascript:void(0);" class="anchorDetail"  data-id="@item.Id">Details</a> 
 
            </td> 
        </tr> 
    } 
 
</table>  

As we can see we have detail anchor, with class anchorDetail and with data-id, which will get the id of clicked anchor and show the corresponding data to modal (detail view) on screen.

We have an Action method Details(int id) which will return the partial view.
public ActionResult Details(int Id) 

    FriendsInfo frnds = new FriendsInfo(); 
    frnds = db.FriendsInfo.Find(Id); 
    return PartialView("_Details",frnds); 
 

Here we added a partial view for this purpose to show detail view when user click on detail anchor in the list.

View Code
@model CodeFirst.Models.FriendsInfo 
 
<div> 
   
    <div class="modal-header"> 
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> 
        <h4 class="modal-title" id="myModalLabel">FriendsInfo</h4> 
    </div>                
                 
     
    <hr /> 
    <dl class="dl-horizontal"> 
        <dt> 
            @Html.DisplayNameFor(model => model.Name) 
        </dt> 
 
        <dd> 
            @Html.DisplayFor(model => model.Name) 
        </dd> 
 
        <dt> 
            @Html.DisplayNameFor(model => model.Mobile) 
        </dt> 
 
        <dd> 
            @Html.DisplayFor(model => model.Mobile) 
        </dd> 
 
        <dt> 
            @Html.DisplayNameFor(model => model.Address) 
        </dt> 
 
        <dd> 
            @Html.DisplayFor(model => model.Address) 
        </dd> 
 
    </dl> 
</div> 


We have a div for modal pop-up.

<div id='myModal' class='modal'> 
    <div class="modal-dialog"> 
        <div class="modal-content"> 
            <div id='myModalContent'></div> 
        </div> 
    </div>  
     
</div>  


Here is the script for showing modal (partial view) on above div when user click on detail anchor. Here we used Ajax call for this purpose.

Script
@section scripts 

    <script src="~/Scripts/jquery-1.10.2.min.js"></script> 
    <script src="~/Scripts/bootstrap.js"></script> 
    <script src="~/Scripts/bootstrap.min.js"></script> 
<script> 
    var TeamDetailPostBackURL = '/Home/Details'; 
    $(function () { 
        $(".anchorDetail").click(function () { 
            debugger; 
            var $buttonClicked = $(this); 
            var id = $buttonClicked.attr('data-id'); 
            var options = { "backdrop": "static", keyboard: true }; 
            $.ajax({ 
                type: "GET", 
                url: TeamDetailPostBackURL, 
                contentType: "application/json; charset=utf-8", 
                data: { "Id": id }, 
                datatype: "json", 
                success: function (data) { 
                    debugger; 
                    $('#myModalContent').html(data); 
                    $('#myModal').modal(options); 
                    $('#myModal').modal('show');                   
 
                }, 
                error: function () { 
                    alert("Dynamic content load failed."); 
                } 
            }); 
        }); 
        //$("#closebtn").on('click',function(){ 
        //    $('#myModal').modal('hide');   
 
        $("#closbtn").click(function () { 
            $('#myModal').modal('hide'); 
        });       
    }); 
    
</script> 
 

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



European ASP.NET Core Hosting - HostForLIFE.eu :: Multiple Models in Single View in MVC

clock February 7, 2020 10:31 by author Peter

In MVC we cannot pass multiple models from a controller to the single view. This article provides a workaround for multiple models in a single view in MVC.

Problem Statement

Suppose I have two models, Teacher and Student, and I need to display a list of teachers and students within a single view. How can we do this?

The following are the model definitions for the Teacher and Student classes.

public class Teacher  
{  
    public int TeacherId { get; set; }  
    public string Code { get; set; }  
    public string Name { get; set; }  
}   
  
public class Student  
{  
    public int StudentId { get; set; }  
    public string Code { get; set; }  
    public string Name { get; set; }  
    public string EnrollmentNo { get; set; }  
}  

The following are the methods that help us to get all the teachers and students.

private List<Teacher> GetTeachers()  
{  
    List<Teacher> teachers = new List<Teacher>();  
    teachers.Add(new Teacher { TeacherId = 1, Code = "TT", Name = "Peter" });  
    teachers.Add(new Teacher { TeacherId = 2, Code = "JT", Name = "Scott" });  
    teachers.Add(new Teacher { TeacherId = 3, Code = "RT", Name = "Paul" });  
    return teachers;  
}   
  
public List<Student> GetStudents()  
{  
    List<Student> students = new List<Student>();  
    students.Add(new Student { StudentId = 1, Code = "L0001", Name = "Thomas", EnrollmentNo = "201404150001" });  
    students.Add(new Student { StudentId = 2, Code = "L0002", Name = "Brian", EnrollmentNo = "201404150002" });  
    students.Add(new Student { StudentId = 3, Code = "L0003", Name = "Chester", EnrollmentNo = "201404150003" });  
    return students;  
}  

There are many ways to use multiple models with a single view. Here I will explain ways one by one.

1. Using Dynamic Model

ExpandoObject (the System.Dynamic namespace) is a class that was added to the .Net Framework 4.0 that allows us to dynamically add and remove properties onto an object at runtime. Using this ExpandoObject, we can create a new object and can add our list of teachers and students into it as a property. We can pass this dynamically created object to the view and render list of the teacher and student.

Controller Code

public class HomeController : Controller  
{  
    public ActionResult Index()  
    {  
        ViewBag.Message = "Welcome to my demo!";  
        dynamic mymodel = new ExpandoObject();  
        mymodel.Teachers = GetTeachers();  
        mymodel.Students = GetStudents();  
        return View(mymodel);  
    }  
}  

We can define our model as dynamic (not a strongly typed model) using the @model dynamic keyword.

View Code

@using MultipleModelInOneView;  
@model dynamic  
@{  
    ViewBag.Title = "Home Page";  
}  
<h2>@ViewBag.Message</h2>  
   
<p><b>Teacher List</b></p>  
   
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
    </tr>  
    @foreach (Teacher teacher in Model.Teachers)  
    {  
        <tr>  
            <td>@teacher.TeacherId</td>  
            <td>@teacher.Code</td>  
            <td>@teacher.Name</td>  
        </tr>  
    }  
</table>  
   
<p><b>Student List</b></p>  
   
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
        <th>Enrollment No</th>  
    </tr>  
    @foreach (Student student in Model.Students)  
    {  
        <tr>  
            <td>@student.StudentId</td>  
            <td>@student.Code</td>  
            <td>@student.Name</td>  
            <td>@student.EnrollmentNo</td>  
        </tr>  
    }  
</table>  

2. Using View Model

ViewModel is nothing but a single class that may have multiple models. It contains multiple models as a property. It should not contain any method. In the above example, we have the required View model with two properties. This ViewModel is passed to the view as a model. To get intellisense in the view, we need to define a strongly typed view.

public class ViewModel  
{  
    public IEnumerable<Teacher> Teachers { get; set; }  
    public IEnumerable<Student> Students { get; set; }  
}  

Controller code

public ActionResult IndexViewModel()  
{  
    ViewBag.Message = "Welcome to my demo!";  
    ViewModel mymodel = new ViewModel();  
    mymodel.Teachers = GetTeachers();  
    mymodel.Students = GetStudents();  
    return View(mymodel);  
}  

View code

@using MultipleModelInOneView;  
@model ViewModel   
@{  
    ViewBag.Title = "Home Page";  
}  
<h2>@ViewBag.Message</h2>  
   
<p><b>Teacher List</b></p>  
   
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
    </tr>  
    @foreach (Teacher teacher in Model.Teachers)  
    {  
        <tr>  
            <td>@teacher.TeacherId</td>  
            <td>@teacher.Code</td>  
            <td>@teacher.Name</td>  
        </tr>  
    }  
</table>  
   
<p><b>Student List</b></p>  
   
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
        <th>Enrollment No</th>  
    </tr>  
    @foreach (Student student in Model.Students)  
    {  
        <tr>  
            <td>@student.StudentId</td>  
            <td>@student.Code</td>  
            <td>@student.Name</td>  
            <td>@student.EnrollmentNo</td>  
        </tr>  
    }  
</table>  

3. Using ViewData
ViewData is used to transfer data from the controller to the view. ViewData is a dictionary object that may be accessible using a string as the key. Using ViewData, we can pass any object from the controller to the view. The Type Conversion code is required when enumerating in the view.
For the preceding example, we need to create ViewData to pass a list of teachers and students from the controller to the view.

Controller Code
public
 ActionResult IndexViewData()  

{  
    ViewBag.Message = "Welcome to my demo!";  
    ViewData["Teachers"] = GetTeachers();  
    ViewData["Students"] = GetStudents();  
    return View();  
}  

View Code

@using MultipleModelInOneView;  
@{  
    ViewBag.Title = "Home Page";  
}  
<h2>@ViewBag.Message</h2>  
 <p><b>Teacher List</b></p>   
@{  
  
   IEnumerable<Teacher> teachers = ViewData["Teachers"] as IEnumerable<Teacher>;  
   IEnumerable<Student> students = ViewData["Students"] as IEnumerable<Student>;  
}  
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
    </tr>  
    @foreach (Teacher teacher in teachers)  
    {  
        <tr>  
            <td>@teacher.TeacherId</td>  
            <td>@teacher.Code</td>  
            <td>@teacher.Name</td>  
        </tr>  
    }  
</table>  
 <p><b>Student List</b></p>  
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
        <th>Enrollment No</th>  
    </tr>  
    @foreach (Student student in students)  
    {  
        <tr>  
            <td>@student.StudentId</td>  
            <td>@student.Code</td>  
            <td>@student.Name</td>  
            <td>@student.EnrollmentNo</td>  
        </tr>  
    }  
</table>  

4. Using ViewBag
ViewBag is similar to ViewData and is also used to transfer data from the controller to the view. ViewBag is a dynamic property. ViewBag is just a wrapper around the ViewData.

Controller Code

public ActionResult IndexViewBag()  
{  
    ViewBag.Message = "Welcome to my demo!";  
    ViewBag.Teachers = GetTeachers();  
    ViewBag.Students = GetStudents();  
    return View();  
}  

View Code

@using MultipleModelInOneView;  
@{  
    ViewBag.Title = "Home Page";  
}  
<h2>@ViewBag.Message</h2>  
   
<p><b>Teacher List</b></p>  
   
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
    </tr>  
    @foreach (Teacher teacher in ViewBag.Teachers)  
    {  
        <tr>  
            <td>@teacher.TeacherId</td>  
            <td>@teacher.Code</td>  
            <td>@teacher.Name</td>  
        </tr>  
    }  
</table>  
   
<p><b>Student List</b></p>  
   
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
        <th>Enrollment No</th>  
    </tr>  
    @foreach (Student student in ViewBag.Students)  
    {  
        <tr>  
            <td>@student.StudentId</td>  
            <td>@student.Code</td>  
            <td>@student.Name</td>  
            <td>@student.EnrollmentNo</td>  
        </tr>  
    }  
</table> 

5. Using Tuple

A Tuple object is an immutable, fixed-size and ordered sequence object. It is a data structure that has a specific number and sequence of elements. The .NET framework supports tuples up to seven elements. Using this tuple object we can pass multiple models from the controller to the view.

Controller Code

public ActionResult IndexTuple() 
{  
    ViewBag.Message = "Welcome to my demo!";  
    var tupleModel = new Tuple<List<Teacher>, List<Student>>(GetTeachers(), GetStudents());  
    return View(tupleModel);  
}  

View Code

@using MultipleModelInOneView;  
@model Tuple <List<Teacher>, List <Student>>  
@{  
    ViewBag.Title = "Home Page";  
}  
<h2>@ViewBag.Message</h2>   
<p><b>Teacher List</b></p>  
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
    </tr>  
    @foreach (Teacher teacher in Model.Item1)  
    {  
        <tr>  
            <td>@teacher.TeacherId</td>  
            <td>@teacher.Code</td>  
            <td>@teacher.Name</td>  
        </tr>  
    }  
</table>  
<p><b>Student List</b></p>  
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
        <th>Enrollment No</th>  
    </tr>  
    @foreach (Student student in Model.Item2)  
    {  
        <tr>  
            <td>@student.StudentId</td>  
            <td>@student.Code</td>  
            <td>@student.Name</td>  
            <td>@student.EnrollmentNo</td>  
        </tr>  
    }  
</table>  

6. Using Render Action Method
A Partial View defines or renders a partial view within a view. We can render some part of a view by calling a controller action method using the Html.RenderAction method. The RenderAction method is very useful when we want to display data in the partial view. The disadvantages of this method is that there are only multiple calls of the controller.


In the following example, I have created a view (named partialView.cshtml) and within this view I called the html.RenderAction method to render the teacher and student list.

Controller Code

public ActionResult PartialView()  
{  
    ViewBag.Message = "Welcome to my demo!";  
    return View();  
}  
   
/// <summary>  
/// Render Teacher List  
/// </summary>  
/// <returns></returns>  
public PartialViewResult RenderTeacher()  
{  
    return PartialView(GetTeachers());  
}  
   
/// <summary>  
/// Render Student List  
/// </summary>  
/// <returns></returns>  
public PartialViewResult RenderStudent()  
{  
    return PartialView(GetStudents());  
 

View Code

@{ 
   ViewBag.Title = "PartialView";  
<h2>@ViewBag.Message</h2>  
<div>  
    @{  
        Html.RenderAction("RenderTeacher");  
        Html.RenderAction("RenderStudent");  
    }  
</div>  

RenderTeacher.cshtml

@using MultipleModelInOneView;  
@model IEnumerable<MultipleModelInOneView.Teacher>  
 <p><b>Teacher List</b></p>  
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
    </tr>  
    @foreach (Teacher teacher in Model)  
    {  
        <tr>  
            <td>@teacher.TeacherId</td>  
            <td>@teacher.Code</td>  
            <td>@teacher.Name</td>  
        </tr>  
    }  
  1. </table>  

RenderStudent.cshtml

@using MultipleModelInOneView;  
@model IEnumerable<MultipleModelInOneView.Student>   
  
<p><b>Student List</b></p>  
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
        <th>Enrollment No</th>  
    </tr>  
    @foreach (Student student in Model)  
    {  
        <tr>  
            <td>@student.StudentId</td>  
            <td>@student.Code</td>  
            <td>@student.Name</td>  
            <td>@student.EnrollmentNo</td>  
        </tr>  
    }  
</table> 

Conclusion

This article helps us to learn how to pass multiple models from the controller to the view. I hope this will be helpful for beginners.



ASP.NET MVC Hosting - HostForLIFE.eu :: Display Mode Provider in MVC 5 Application

clock January 22, 2020 10:19 by author Peter

This article will solve a problem. Display modes in ASP.NET MVC 5 provide a way of separating page content from the way it is rendered on various devices, like web, mobile, iPhone, iPod and Windows Phones. All you need to do is to define a display mode for each device, or class of devices.

First you create a model and context class. We create an Employee class that has the following properties like.
    public class Employee 
    { 
        public Guid ID { get; set; } 
        [Display(Name="First Name")] 
        public string FirstName { get; set; } 
        [Display(Name = "Last Name")] 
        public string LastName { get; set; } 
        [Display(Name = "Department")] 
        public string Department { get; set; } 
        [Display(Name = "Salary")] 
        public double Salary { get; set; } 
        [Display(Name = "Address")] 
        public string Address { get; set; } 
    }


And second is the context class like this that inherits the DbContext class.
    public class DBConnectionContext:DbContext 
    {         
       public DBConnectionContext(): base("name=dbContext") 
       { 
             Database.SetInitializer(new DropCreateDatabaseIfModelChanges 
             <DBConnectionContext>()); 
       } 
            public DbSet<Employee> Employees { get; set; } 
    }


If you want to recreate data every time the model changes, add these lines of code.
    Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DbConnectionContext>());

You also have a web config file. We configure connectionStrings in the Web.Config file.
    <connectionStrings> 
    <add name="dbContext" connectionString="Data Source=localhost; Initial Catalog=CommonDataBase; Integrated Security=true"  
          providerName="System.Data.SqlClient" /> 
     </connectionStrings>


Then you create a controller class in a controller folder and edit the name as HomeController. Add a Scaffold to select a MVC 5 Controller with Views, using Entity Framework.

DisplayModes

DisplayModes give you another level of flexibility on top of the default capabilities we saw in the last section. DisplayModes can also be used along with the previous feature so we will simply build off of the site we just created. Let's say we wanted to show an alternate view for the Windows Phone 8, iPhone, iPod or Android.

Windows Phone 8 DisplayMode

Now that you have made the override files, you can use a DisplayMode to show them for the appropriate phones.

The best time to set this up is when the application starts. Here is our global.asax.cs, with the DisplayMode setup.
    DisplayModeProvider.Instance.Modes.Insert(1, new DefaultDisplayMode("WP") 
    { 
        ContextCondition = (ctx => ctx.GetOverriddenUserAgent() 
        .IndexOf("Windows Phone OS", StringComparison.OrdinalIgnoreCase) > 0)   
     }); 
      
    DisplayModeProvider.Instance.Modes.Insert(1, new DefaultDisplayMode("iPhone") 
    { 
        ContextCondition = (ctx => ctx.GetOverriddenUserAgent() 
        .IndexOf("iPhone", StringComparison.OrdinalIgnoreCase) > 0)   
    }); 
      
    DisplayModeProvider.Instance.Modes.Insert(1, new DefaultDisplayMode("Android") 
    { 
        ContextCondition = (ctx => ctx.GetOverriddenUserAgent() 
        .IndexOf("Android", StringComparison.OrdinalIgnoreCase) > 0)   
    }); 

The DisplayModeProvider Class
DisplayModeProvider holds a list of DefaultDisplayMode obejects, each representing display mode. And the provider holds the two display modes, default and mobile. The default display mode in an empty string and the second holds the mobile string.


We just create multiple View with [View].Android.cshtml, [View].iPhone.cshtml and so on for every device such as:

We create an index for iPhone and create a new employee in iPhone Index.iPhone.cshtml and Create.iPhone.cshtml.


We create an index for Windows Phone and create a new employee in the Windows Phone Index.WP.cshtml Create.WP.cshtml.


We create an index for Android and create a new employee in Windows Phone Index.Android.cshtml Create.Android.cshtml.



ASP.NET MVC Hosting - HostForLIFE.eu :: Prepare a Custom JSON Format in MVC or Remove JSON Key

clock January 9, 2020 11:15 by author Peter

This post explains how to remove a JSON key in JSON result in MVC or C#

We can create our own converter class:
    public class JsonKeysConverter : JsonConverter 
    { 
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 
        { 
            Module o = (Module)value; 
            JObject newObject = new JObject(new JProperty(o.Name, o.Permission)); 
            newObject.WriteTo(writer); 
        } 
     
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 
        { 
            throw new NotImplementedException("The type will skip the converter."); 
        } 
     
        public override bool CanRead 
        { 
            get { return false; } 
        } 
     
        public override bool CanConvert(Type objectType) 
        { 
            return true; 
        } 
    } 
     
    [JsonConverter(typeof(JsonKeysConverter))] 
    public class Module 
    { 
        public string Name { get; set; } 
        public string[] Permission { get; set; } 
    } 
     
    public class Role 
    { 
        public class Roles 
        { 
            public Dictionary<string, List<string>> Modules {get; set;} 
        } 
    } 
     
    public static string json() 
    { 
            var oRoles = new Roles(); 
            oRoles.modules = new Module[] { 
                new Module(){ 
                    Name="Page-Profile", 
                    Permission=new string[]{ "Edit","View","Delete"} 
                }, 
                new Module(){ 
                    Name="User", 
                    Permission=new string[]{ "Edit","View","Delete","Update"} 
                } 
            }; 
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(oRoles); 
         
                     
            Dictionary<string, List<string>> modules = new Dictionary<string, List<string>>(); 
            modules.Add("Page-Profile", new List<string>() { "Edit", "View", "Delete"}); 
            modules.Add("User", new List<string>() { "Edit", "View", "Delete", "Update"}); 
             
            return JsonConvert.SerializeObject(modules);  


Output
{"Page-Profile":["Edit","View","Delete"],"User":["Edit","View","Delete","Update"]}  



ASP.NET MVC Hosting - HostForLIFE.eu :: How to Use Google Calendar API?

clock December 6, 2019 11:27 by author Peter

In this article I will show you how to use Google Calendar in ASP.NET MVC. Google APIs use the OAuth 2.0 protocol for authentication and authorization. Google supports common OAuth 2.0 scenarios such as those for web server, installed, and client-side applications.It's more easily to log in your application via OAuth and OpenID provider in  ASP.NET MVC 4 now. Microsoft has few build-in client for Microsoft, Twitter, Facebook, Google. The Google client is based on OpenID and not OAuth. That's mean you can not access Google Data API.

In order to access Google Data API for web application. You need to register a Client ID to get Client ID an Client Secret for setting in your application.

You need to assign redirect URIs for grap OAuth access token callback also. Here we setup Rirect URIs as http://localhost:57271/Account/ExternalLoginCallback.

Google Client Library for .NET

The Google APIs Client Library for .NET is generic .NET runtime client for Google Services. The library supports OAuth2.0 authentication, and is able to generate strongly typed client libraries for Discovery-based services. Google Client library is a higher level library for using Google Data API. You can download beta version from Nuget in visual studio. It's more difficult to handle Google Client Library for .NET with few documents and sample now. Here, just using Google.Apis.Calendar.v3.Data namespace to our strong type class for data binding in deserialize object from API response.

    private Event GoogleEventHandle(string token, string method, string requestURL, string requestBody = null)
        {
            var jsonSerializer = new JavaScriptSerializer();
            var request = WebRequest.Create(requestURL) as HttpWebRequest;
            request.KeepAlive = true;
            request.ContentType = "application/json";
            request.Method = method;
            request.Headers.Add("Authorization", "Bearer " + token);

            if(requestBody != null)
            {
                Stream ws = request.GetRequestStream();
                using (var streamWriter = new StreamWriter(ws, new UTF8Encoding(false)))
                {
                    streamWriter.Write(requestBody);
                }
            }

            var response = request.GetResponse();
            var stream = new StreamReader(response.GetResponseStream());

            var googleEvent = Newtonsoft.Json.JsonConvert.DeserializeObject(stream.ReadToEnd().Trim());

            return googleEvent; 
        }

        private Event CreateGoogleEvent(string token, string calendarId, string requestBody)
        {
            var requestURL = string.Format("https://www.googleapis.com/calendar/v3/calendars/{0}/events", calendarId);
            return GoogleEventHandle(token, "POST", requestURL, requestBody);             
        }

Above is methods how we are accessing Google Calendar v3 API via webrequest. Now, we are be able to access Google Calendar API via OAuth. Nest step, we will create a simple CRUD UI by AngularJS.


HostForLIFE.eu ASP.NET MVC Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.



ASP.NET MVC Hosting - HostForLIFE.eu :: ASP.NET MVC 5 Create Shared Razor Layout And ViewStart

clock October 25, 2019 09:18 by author Peter

In article, I have shared a way to create a Layout Razor and ViewStart in ASP.NET MVC 5.
 
Views/Shared
You need to create a shared folder, "Shared" in the Views directory.
 
Go Views/Shared directory and create new _LayoutPage1.cshtml file and write the following below code.
    <!DOCTYPE html> 
     
    <html> 
    <head> 
        <meta name="viewport" content="width=device-width" /> 
        <title>@ViewBag.Title</title> 
    </head> 
    <body> 
        <div> 
            @RenderBody() 
        </div> 
    </body> 
    </html> 


The @RenderBody()
Use display content in multiple controllers to View.

Example you can have a fixed header and footer in the page. Only change will be the content of the RenderBody() called in the code.
    <html> 
    <head> 
        <meta name="viewport" content="width=device-width" /> 
        <title>@ViewBag.Title</title> 
    </head> 
    <body> 
        <div class="header"> 
            <!--code header fixed--> 
        </div> 
        <div> 
            @RenderBody() 
        </div> 
        <div class="footer"> 
            <!--code footer fixed--> 
        </div> 
    </body> 
    </html> 


So you have fixed the (header/footer) for the website.
 
Okay, you need using _LayoutPage1.cshtml, so you to Views/Home/index.cshtml. Open it, pass the following below code.
    @{ 
        ViewBag.Title = "Index"; 
        Layout = "~/Views/Shared/_LayoutPage1.cshtml"; 
    } 


_ViewStart.cshtml used to define the layout for the website. You can set the layout settings as well, if HomeController is using Layout.
 
_LayoutHome.cshtml or AdminController is _LayoutAdmin.cshtml
    //Views/ViewStart.cshtml 
    @{ 
        Layout = "~/Views/Shared/_LayoutPage1.cshtml"; 
    } 


You can configuration _ViewStart.cshtml the following below code.
    @{ 
     
        string CurrentName = Convert.ToString(HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"]); 
        string clayout = ""; 
        switch (CurrentName) 
        { 
            case "Home": 
                clayout = "~/Views/Shared/_LayoutHome.cshtml"; 
                break; 
            default: 
                //Admin layout   
                clayout = "~/Views/Shared/_LayoutAdmin.cshtml"; 
                break; 
        } 
        Layout = clayout; 
     
    } 

This gives you an idea, how to use a Razor layout in various pages.

 



ASP.NET MVC Hosting - HostForLIFE.eu :: Preventing Cross Site Request Forgery In MVC

clock September 26, 2019 11:14 by author Peter

What is Cross-Site Request Forgery
Cross-Site Request Forgery (CSRF) is a process in which a user first signs on to a genuine website (e.g. facebook.com) and after successful login, the user opens another website (malicious website) in the same browser.
 
Both websites are opened in the same browser. Malicious website will display some links to the user and asks the user to click on those links. User clicks on the links displayed on a malicious website, the malicious website sends a request using the existing session of genuine website. Web server of genuine website treats this request as a valid request and assumes that it is coming from a valid user so it executes the request and provides a proper response. A malicious website can perform harmful operations on genuine website.
 
In order to solve this problem, we expect the Action Method of genuine website to recognize the source of the request, whether the request is coming from genuine website or from a malicious website. This can be achieved by using the [ValidateAntiForgeryToken] attribute in ASP.Net MVC.
 
How to Implement CSRF Security in MVC
In order to implement CSRF security in MVC, first, we need to use HTML helper @Html.AntiForgeryToken() in view. It should be placed inside the BeginForm() method in view.
 
Next, we need to add [ValidateAntiForgeryToken] attribute on the action method which will accept HTTP post request. We need to do only these 2 changes and now MVC will prevent CSRF attacks.
 
How ValidateAntiForgeryToken works
How ValidateAntiForgeryToken prevents CSRF attacks?


First, the user will open genuine website in the browser. User login to genuine website. After login, genuine website sends Authentication cookie and Verification token. Verification token has randomly generated alphanumeric values. The verification token is stored in the cookie as well as in hidden field on client-side. When HTML form is submitted to the server, the verification token is submitted as a cookie as well as a hidden field. On the server-side, both are checked if they are same or not? If both are same then request is valid. If they are different or one of them is missing then request is treated as invalid request and will be rejected automatically by MVC.
 
When a user opens a malicious website in a new tab of the same browser, the malicious website will display some links and ask the user to click on those links. This website already has a script to send the request to genuine website. When the user clicks on links, the malicious website sends a request to genuine website. Since request is being sent to genuine website, the browser automatically submits Authentication cookie to Action method of genuine website but here, the hidden field is missing. The Action method has [ValidateAntiForgeryToken] attribute so it checks whether Authentication cookie and hidden field has same value but here, the hidden field is missing so the request is treated as invalid and it is rejected by MVC.
 
Practical Implementation
Wherever you have a Form, use @Html.AntiForgeryToken() inside the form and action method for accepting the HTTP Post should have ValidateAntiForgeryToken attribute. These are the only change, the rest of the process will be taken care of by ASP.Net MVC.
 
Please see the below HTML view where I have [email protected]()
    @using (Html.BeginForm("Create", "Products", FormMethod.Post, new { enctype = "multipart/form-data" })) 
    { 
       @Html.AntiForgeryToken() 
       <div class="form-row"> 
       <div class="form-group col-md-6"> 
          @Html.LabelFor(temp => temp.ProductName) 
          @Html.TextBoxFor(temp => temp.ProductName, new { placeholder = "Product Name", @class = "form-control" }) 
          @Html.ValidationMessageFor(temp => temp.ProductName) 
       </div> 
    <div class="form-group col-md-6"> 
       @Html.LabelFor(temp=>temp.Price) 
       @Html.TextBoxFor(temp=>temp.Price,new { @class="form-control",placeholder="Price"}) 
    </div> 
    </div> 
    @Html.ValidationSummary() 
       <button type="submit" class="btn btn-success">Create</button> 
       <a class="btn btn-danger" href="/products/index">Cancel</a> 
    } 

Below is the action method where I have added [ValidateAntiForgeryToken] attribute.
    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Create(Product p) 
       { 
       ProductDBContext db = new ProductDBContext(); 
       if (ModelState.IsValid) 
       { 
          db.Products.Add(p); 
          db.SaveChanges(); 
          return RedirectToAction("Index"); 
       } 
       else 
       { 
          return View(); 
    } 
    } 

Summary
In this blog, I have explained Cross-Site Request Forgery(CSRF), its steps and what changes we need to do in MVC application to prevent CSRF attacks.



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