European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Display A Document From SQL Server To A Web Page In ASP.NET MVC

clock October 27, 2020 10:19 by author Peter

In this blog post, I'll discuss a useful yet easy to implement document viewer API. Using that you can display a source file (e.g. Word, Presentation, Diagram, PSD) from your server to your browser without downloading it.
 

Some Use-Cases
    Display a Word resume to a user in a web browser
    Render a Visio Diagram on the web page
    View a Presentation or a Slide online without downloading it

Implementation
 
Now as the use-cases are clear, we will dive into the API implementation. It'll be an ASP.NET MVC application. We'll pull data/documents from the database and save it to a stream. You have to specify the file format in order to render it correctly. The source document will be then rendered to HTML. Eventually, our controller will return this stream to the View/browser.  
    public ActionResult Index()  
    {  
         License lic = new License();  
         lic.SetLicense(@"D:/GD Licenses/Conholdate.Total.NET.lic");  
         MemoryStream outputStream = new MemoryStream();  
         //specify just the file name if you are pulling the data from database   
         string fileName = "sample.pdf";  
      
         FileType fileType = FileType.FromExtension(Path.GetExtension(fileName));  
      
         using (Viewer viewer = new Viewer(() => GetSourceFileStream(fileName), () => new LoadOptions(fileType)))  
         {  
               HtmlViewOptions Options = HtmlViewOptions.ForEmbeddedResources(  
                    (pageNumber) => outputStream,  
                    (pageNumber, pageStream) => { });  
               viewer.View(Options);  
         }
         outputStream.Position = 0;  
         return File(outputStream, "text/html");  
                   
    }  
    private Stream GetSourceFileStream(string fileName) =>  
                new MemoryStream(GetSourceFileBytesFromDb(fileName));  
      
    //TODO: If you want to pull the data from the DB  
    private byte[] GetSourceFileBytesFromDb(string fileName) =>  
                System.IO.File.ReadAllBytes(fileName);  


Have a look at this image/screenshot. We displayed a PDF from Server to Browser.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: ViewBag, ViewData And TempData In MVC

clock October 23, 2020 09:44 by author Peter

ViewBag, ViewData, and TempData all are objects in ASP.NET MVC and these are used to pass the data in various scenarios.

The following are the scenarios where we can use these objects.
    Pass the data from Controller to View.
    Pass the data from one action to another action in the same Controller.
    Pass the data in between Controllers.
    Pass the data between consecutive requests.

ViewBag
ViewBag is a dynamic object to pass the data from Controller to View. And, this will pass the data as a property of object ViewBag. And we have no need to typecast to read the data or for null checking. The scope of ViewBag is permitted to the current request and the value of ViewBag will become null while redirecting.
 
Ex Controller
    Public ActionResult Index()  
    {  
        ViewBag.Title = “Welcome”;  
        return View();  
    }  

View
    <h2>@ViewBag.Title</h2>  

ViewData
ViewData is a dictionary object to pass the data from Controller to View where data is passed in the form of key-value pair. And typecasting is required to read the data in View if the data is complex and we need to ensure null check to avoid null exceptions. The scope of ViewData is similar to ViewBag and it is restricted to the current request and the value of ViewData will become null while redirecting.
 
Ex
Controller:

    Public ActionResult Index()  
    {  
        ViewData[”Title”] = “Welcome”;  
        return View();  
    }  


View
    <h2>@ViewData[“Title”]</h2>  

TempData
TempData is a dictionary object to pass the data from one action to other action in the same Controller or different Controllers. Usually, TempData object will be stored in a session object. Tempdata is also required to typecast and for null checking before reading data from it. TempData scope is limited to the next request and if we want Tempdata to be available even further, we should use Keep and peek.
 
Ex - Controller
    Public ActionResult Index()  
    {  
        TempData[”Data”] = “I am from Index action”;  
        return View();  
    }  

    Public string Get()  
    {  
        return TempData[”Data”] ;  
    }  

To summarize, ViewBag and ViewData are used to pass the data from Controller action to View and TempData is used to pass the data from action to another action or one Controller to another Controller.
 
Hope you have understood the concept of ViewBag, ViewData, and TempData.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Adding Robots.txt to your ASP.NET MVC Applications?

clock September 23, 2020 08:49 by author Peter

One of the things I always forgot to add to my web applications is the Robots.txt file that Search Engines use to see what they should index. This file and sitemaps help make your site easier to navigate by the bots and allow them to understand what's legal and what you'd rather not have the revealed in their engines. I usually add any administrative pages or account pages even though they're protected by security, no need for the login page to be index if they sniff the link.

So how do you add Robots.txt to your MVC application? Glad you asked, here is a little code to get you started.

Sample Code

1.  Select the controller you would like to use for the robots.txt output.  I chose the HomeController in my application as I use it for most “top level” generic links like about us, contact us, index, etc.

2. Now, create a method called Robots to handle the request.
#region -- Robots() Method --
public ActionResult Robots()
{
    Response.ContentType = "text/plain";
    return View();
}
#endregion


3. Add the Robots.cshtml view to your Controller’s View directory.  Here is the code I have in my view, yours will vary.
@{
    Layout = null;
}
# robots.txt for @this.Request.Url.Host
User-agent: *
Disallow: /Administration/
Disallow: /Account/


4. Load up the class you are using to control your routes, if you are in an Area, this could your AreaRegistration class.  If you are at the top like I am and using the standard MVC template, this is probably the Global.asax.cs file.  Add your route to this file, mine looks like this.

routes.MapRoute("Robots.txt",

                "robots.txt",

                new { controller = "Home", action = "Robots" });


5. Compile and test.

If you've got an internet facing site, the chances are you will have a bot find you're request this page. you might as well give them the benefit of the doubt and allow them to understand where you want them to go. additionally you may save yourself some error log when this page is requested and no controller is found.

Just like something in ASP.NET, there are many ways to solve this riddle, if you use a different approach, please feel free to share it in the comments.

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



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Display A Document From SQL Server To A Web Page In ASP.NET MVC

clock September 9, 2020 09:24 by author Peter

In this blog post, I'll discuss a useful yet easy to implement document viewer API. Using that you can display a source file (e.g. Word, Presentation, Diagram, PSD) from your server to your browser without downloading it.
 
Some Use-Cases
    Display a Word resume to a user in a web browser
    Render a Visio Diagram on the web page
    View a Presentation or a Slide online without downloading it

Implementation

Now as the use-cases are clear, we will dive into the API implementation. It'll be an ASP.NET MVC application. We'll pull data/documents from the database and save it to a stream. You have to specify the file format in order to render it correctly. The source document will be then rendered to HTML. Eventually, our controller will return this stream to the View/browser.  
    public ActionResult Index()  
    {  
         License lic = new License();  
         lic.SetLicense(@"D:/GD Licenses/Conholdate.Total.NET.lic");  
         MemoryStream outputStream = new MemoryStream();  
         //specify just the file name if you are pulling the data from database   
         string fileName = "sample.pdf";  
      
         FileType fileType = FileType.FromExtension(Path.GetExtension(fileName));  
      
         using (Viewer viewer = new Viewer(() => GetSourceFileStream(fileName), () => new LoadOptions(fileType)))  
         {  
               HtmlViewOptions Options = HtmlViewOptions.ForEmbeddedResources(  
                    (pageNumber) => outputStream,  
                    (pageNumber, pageStream) => { });  
               viewer.View(Options);  
         }
         outputStream.Position = 0;  
         return File(outputStream, "text/html");  
                   
    }  
    private Stream GetSourceFileStream(string fileName) =>  
                new MemoryStream(GetSourceFileBytesFromDb(fileName));  
      
    //TODO: If you want to pull the data from the DB  
    private byte[] GetSourceFileBytesFromDb(string fileName) =>  
                System.IO.File.ReadAllBytes(fileName);  


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



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Using Auto-Mapper In An ASP.NET Core MVC Application

clock August 25, 2020 08:24 by author Peter

In today’s article we will look at an extremely useful feature. In many applications, the data we collect on the user interface needs to be converted to some different form before it can be stored in the data store and vice versa. This requires some mapping logic and it is mostly done using mapping classes and logic. Today, we will look at a ready to use Nuget package to do this mapping for us and make the process amazingly simple. We will apply this mapping in an ASP.NET Core MVC application.

Creating the .NET Core MVC application
We will start by creating an ASP.NET Core 3.1 MVC application using Visual Studio 2019 community edition as below,

We select the ASP.NET Core web application and click “Next”

Next, we enter the project details and click “Create”

From the list of ASP.NET Core web applications, we select “Web Application (Model-View-Controller) and leave all other values as default.
 
We now have the ASP.NET Core MVC application created. The next step is to add the “AutoMapper” Nugget package as below,

Remember to select the latest version.

After that create three classes under the “Models” folder as below,
 
Employee.cs

    namespace WebAppAutoMapper.Models { 
        publicclassEmployee { 
            publicstring FirstName { 
                get; 
                set; 
            } 
            publicstring LastName { 
                get; 
                set; 
            } 
            publicstring StreetAddress { 
                get; 
                set; 
            } 
            publicstring City { 
                get; 
                set; 
            } 
            publicstring Province { 
                get; 
                set; 
            } 
            publicstring Country { 
                get; 
                set; 
            } 
            publicstring Email { 
                get; 
                set; 
            } 
            publicstring Phone { 
                get; 
                set; 
            } 
            publicEmployee() { 
                FirstName = "Munib"; 
                LastName = "Butt"; 
                StreetAddress = "123 Street One"; 
                City = "Toronto"; 
                Province = "Ontario"; 
                Country = "Canada"; 
                Email = "[email protected]"; 
                Phone = "+14161112222"; 
            } 
        } 
    } 

EmployeeDTO.cs

    namespace WebAppAutoMapper.Models { 
        publicclassEmployeeDTO { 
            publicstring Name { 
                get; 
                set; 
            } 
            publicstring Address { 
                get; 
                set; 
            } 
            publicstring Email { 
                get; 
                set; 
            } 
            publicstring Phone { 
                get; 
                set; 
            } 
        } 
    } 

And finally,AutoMap.cs

    using AutoMapper; 
     
    namespace WebAppAutoMapper.Models 
    { 
    publicclassAutoMap : Profile 
        { 
    publicAutoMap() 
            { 
                CreateMap<Employee, EmployeeDTO>() // means you want to map from Employee to EmployeeDTO 
                .ForMember(d => d.Name, source => source.MapFrom(s => s.FirstName + " " + s.LastName)) 
                .ForMember(d => d.Address, source => source.MapFrom(s => s.StreetAddress + ", " + s.City + ", " + s.Province + ", " + s.Country)) 
                .ForMember(d => d.Phone, source => source.MapFrom(s => s.Phone)) 
                .ForMember(d => d.Email, source => source.MapFrom(s => s.Email)); 
            } 
        } 
    } 

Here we see that we have an Employee class which has several properties. We also have an EmployeeDTO class which has fewer properties than the Employee class. Now, we want to map the values from the Employee class to the EmployeeDTO class using some mapping logic. This logic is implemented in the AutoMap.cs class which inherits from the Profile class.
 
Finally, we setup the AutoMap in the Startup.cs class in the “ConfigureServices” function as below,

    using Microsoft.AspNetCore.Builder; 
    using Microsoft.AspNetCore.Hosting; 
    using Microsoft.Extensions.Configuration; 
    using Microsoft.Extensions.DependencyInjection; 
    using Microsoft.Extensions.Hosting; 
    using AutoMapper; 
    using WebAppAutoMapper.Models; 
     
    namespace WebAppAutoMapper 
    { 
    publicclassStartup 
        { 
    publicStartup(IConfiguration configuration) 
            { 
                Configuration = configuration; 
            } 
     
    public IConfiguration Configuration { get; } 
     
    // This method gets called by the runtime. Use this method to add services to the container. 
    publicvoid ConfigureServices(IServiceCollection services) 
            { 
                services.AddAutoMapper(c => c.AddProfile<AutoMap>(), typeof(Startup)); 
                services.AddControllersWithViews(); 
            } 
     
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
    publicvoid Configure(IApplicationBuilder app, IWebHostEnvironment env) 
            { 
    if (env.IsDevelopment()) 
                { 
                    app.UseDeveloperExceptionPage(); 
                } 
    else 
                { 
                    app.UseExceptionHandler("/Home/Error"); 
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. 
                    app.UseHsts(); 
                } 
                app.UseHttpsRedirection(); 
                app.UseStaticFiles(); 
     
                app.UseRouting(); 
     
                app.UseAuthorization(); 
     
                app.UseEndpoints(endpoints => 
                { 
                    endpoints.MapControllerRoute( 
                        name: "default", 
                        pattern: "{controller=Home}/{action=Index}/{id?}"); 
                }); 
            } 
        } 
    } 

Now, all the plumbing is in place and we can use the mapping as below in the Home Controller,

    using System.Diagnostics; 
    using Microsoft.AspNetCore.Mvc; 
    using Microsoft.Extensions.Logging; 
    using WebAppAutoMapper.Models; 
    using AutoMapper; 
     
    namespace WebAppAutoMapper.Controllers 
    { 
    publicclassHomeController : Controller 
        { 
    privatereadonly ILogger<HomeController> _logger; 
    privatereadonly IMapper _mapper; 
     
    publicHomeController(ILogger<HomeController> logger, IMapper mapper) 
            { 
                _logger = logger; 
                _mapper = mapper; 
            } 
     
    public IActionResult Index() 
            { 
                Employee emp = new Employee(); 
    var empDTO = _mapper.Map<EmployeeDTO>(emp); 
    return View(); 
            } 
     
    public IActionResult Privacy() 
            { 
    return View(); 
            } 
     
            [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] 
    public IActionResult Error() 
            { 
    return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); 
            } 
        } 
    } 

We can put a breakpoint at the “return View();” line in the Index function and see the Employee DTO values as below,

Here we see that the empDTO object has the values extracted and mapped from the Employee object.

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

 



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: TempData in ASP.NET MVC 6

clock August 7, 2020 13:02 by author Peter

In this Article, we will discuss about TempData. TempData in ASP.NET MVC can be used to store temporary data which can be used in the subsequent request. TempData will be cleared out after the completion of a subsequent request.

TempData is useful when you want to transfer non-sensitive data from one action method to another action method of the same or a different controller as well as redirects. It is dictionary type which is derived from TempDataDictionary.

You can add a key-value pair in TempData as shown in the below example.

TempData allows you to store data & it will remain after redirects. It uses the Session to store data. When an object in a TempDataDictionary. It will be marked for deletion at the end of that request.

TempData declared as

TempData["value"] = "data";

Example


public ActionResult FirstAction()

{
    // store something into the tempdata that will be available during a single redirect
    TempData["FirstAction"] = "SecondAction";
    // you should always redirect if you store something into TempData to
    // a controller action that will consume this data
    return RedirectToAction("SecondAction");
}
public ActionResult SecondAction()
{    var data = TempData["FirstAction"];
   return View();
}

 
The Peek and Keep methods allow to read the value without deletion. we can say that first request data will remains in TempData. You can use Peek when you always want to retain the value for another request. Use Keep when retaining the value depends on additional logic.

//second request, Peek value is not deleted at the end of the request
object value = TempData.Peek("value");

//third request, read value and delete
object value = TempData["value"];

 

Keep
//second request, get value going for delete

object value = TempData.["value"];

//later  decide to keep it for next request
TempData.Keep("value");

//third request, read value and mark it for deletion
object value = TempData["value"];

Removing TempData

TempData.Clear() : It is use to remove all keys from the TempDataDictionary TempData.Remove(key) :Remove a specific key from TempDataDictionary.

Note: Since TempData makes use of the Session State behavior, it must be enabled on the controller using TempData. By default it is always enabled, You can disable session state for your controllers by adding [SessionState(SessionStateBehavior.Disabled)] attribute.

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



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Handle Multiple Submit Buttons in ASP.NET MVC 6?

clock July 30, 2020 13:16 by author Peter

Today, let me explain you how to handle multiple submit buttons in ASP.NET MVC 6. Sometimes you will need to handle multiple submit buttons on a similar form as as in the following picture.

As you can see on the above picture, we've got the three buttons Login, Register and Cancel. Here every button has totally different functionality. in this way every submit button will post a form to the server but will provide totally different values of every button.

Make a controller with one action method that accepts other parameters, one is for the model and the other is for determining the status of the button click.
[HttpPost] 
public ActionResult Index(Login model, string command) 

if (command=="Login") 

// do stuff 
return RedirectToAction("Home"); 

else if (command=="Register") 

// do stuff 
ViewBag.msg = "You have Clicked Register button"; 
return View(); 


else if (command=="Cancel") 

// do stuff 
ViewBag.msg = "You have Clicked Cancel Button"; 
return View(); 

else 

return View(); 



In the preceding code snippet, assume you clicked on the Login button, then the command parameter can have the values Login, null, null respectively. Create a View for the preceding controller.
@model MvcMultipleSubmitButtons.Models.Login 
@{ 
ViewBag.Title = "Index"; 

<h2> 
Handling multiple submit buttons in MVC </h2> 
<h5 style="color: Red">@ViewBag.msg</h5> 
<form action="Home/Index" id="myform" method="post" >  
//here action name is Index, controller name is Home. So the action path is Home/Index 
<table> 
<tr> 
<td> 
UserName 
</td> 
<td> 

</td> 
<td>@Html.TextBoxFor(m => m.userName) 
</td> 
<td> 
@Html.ValidationMessageFor(m => m.userName) 
</td> 
</tr> 
<tr> 
<td> 
Password 
</td> 
<td> 

</td> 
<td>@Html.TextBoxFor(m => m.password) 
</td> 
<td> 
@Html.ValidationMessageFor(m => m.password) 
</td> 
</tr> 
</table> 
<br/> 

<div style="padding-left: 80px;"> 
<input type="submit" id="Login" value="Login" name="Command" title="Login" /> 
<input type="submit" id="Register" value="Register" name="Command" title="Register" /> 
<input type="submit" value="Cancel" name="Command" title="Cancel" /> 

</div> 
</form> 


You can declare the form tag in another way as within the following:
@using(Html.BeginForm("Index","Home",FormMethod.Post)) 
{  
//here action name is Index, controller name is Home and form method is post. 
}


Note: there's a relation between button name and action method parameter. for instance, the button name is “Command”, the action parameter name ought to be “command”.

You can have different names for each button. So in that case you need to handle it as in the following:
<input type="submit" id="Login" value="Login" name="Command1" title="Login" /> 
<input type="submit" id="Register" value="Register" name="Command2" title="Register" /> 
<input type="submit" value="Cancel" name="Command3" title="Cancel" /> 


Controller
public ActionResult Index(Login model, string command1, string command2, string command3) 

   // here command1 is for Login, command2 is for Register and command3 is for cancel 


Create a Model class with the name Login.
public class Login 

    public string userName { get; set; } 
    public string password { get; set; } 

I hope it helps for you!

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



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Action Filter In MVC

clock July 3, 2020 14:12 by author Peter

Action filter in MVC provides the option to handle the situations after we would really like to perform an operation before and after the execution of a controller action. For this purpose, we create a custom class, which inherits the FilterAttribute class and implements the IActionFilter interface. when creating the filter, we simply apply the class name as an attribute on the controller.

Here, the FilterAttribute class makes it possible to use the class as an attribute and IActionFilter interface contains two methods named OnActionExecuting and OnActionExecuted. The OnActionExecuting is executed before the controller method is executed and OnActionExecuted is called after the execution of the controller method. This kind of technique is quite helpful for the logging purposes. Thus, let's see how we can use this filter.
 
Let's start by adding a new class named MyActionFilter.cs. Now, derive this class from the FilterAttribute and the IActionFilter. Implement the  OnActionExecuting and OnActionExecuted methods and add your custom logic into the methods.Thus, the code will look as shown below. 
    public class MyActionFilter : FilterAttribute, IActionFilter 
    { 
        public void OnActionExecuted(ActionExecutedContext filterContext) 
        { 
            //Fires after the method is executed 
        } 
     
        public void OnActionExecuting(ActionExecutingContext filterContext) 
        { 
            //Fires before the action is executed 
        } 
    } 


Simply, apply the class as an attribute on the controller. Add debuggers on both the methods as well as the controller method.
    public class HomeController : Controller 
    { 
        [MyActionFilter] 
        public ActionResult Index() 
        { 
            return View(); 
        } 
     
        public ActionResult About() 
        { 
            ViewBag.Message = "Your application description page."; 
            return View(); 
        } 
     
        public ActionResult Contact() 
        { 
            ViewBag.Message = "Your contact page."; 
            return View(); 
        } 
    } 


Run the Application and debug step by step to see the order of execution of the methods. First, the OnActionExecuting will be executed, then the controller method and finally the OnActionExecuted method.

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



ASP.NET MVC 6 Hosting UK - HostForLIFE.eu :: How to Delete Multiple Items in ASP.NET with JSON?

clock June 26, 2020 13:15 by author Peter

Today, I want to show you how to delete multiple Items in ASP.NET with JSON. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language. Now, open your project and write the following code:

View
<table class="table"> 
@foreach (var role in Model) { 
<tr> 
    <td> 
        <input id="responsable1" name="checkResp" value="@role.id" type="checkbox" /> 
        <strong>@role.Name</strong> 
    </td> 
</tr> 

</table> 
<input id="DeleteBtn" type="button" value="Delete Selected" /> 
<script> 
$("#DeleteBtn").on("click", function() { 
    var boxData = []; 
    $("input[name='checkResp']:checked").each(function() { 
        boxData.push($(this).val()); 
    }); 
    $.ajax({ 
        url: '/Roles/DeleteMultiple', 
        data: { 
            RoleId: boxData.join(",") 
        }, 
        cache: false, 
        type: "POST", 
        timeout: 10000, 
        dataType: "json", 
        success: function(result) { 
            window.location.reload(); 
        } 
    }); 
}); 
</script> 


Controller
[HttpPost] 
public JsonResult DeleteMultiple(string RoleId) { 
ApplicationDbContext db = new ApplicationDbContext(); 
var RoleIds = RoleId.Split(','); 
foreach(var id in RoleIds) { 
    int idConverted = Convert.ToInt32(id); 
    Roles roleid = db.Roles.Find(idConverted); 
    db.Roles.Remove(roleid); 

context.SaveChanges(); 
var message = "Selected roles have been deleted"; 
return Json(message); 


DeleteMultiple - Action Name
Roles - Controller Name

 

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



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



About HostForLIFE

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in