European ASP.NET MVC 4 and MVC 5 Hosting

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

ASP.NET MVC Hosting - HostForLIFE.eu :: Using Ajax in MVC Application

clock June 21, 2016 00:16 by author Anthony

In asp.net web form application, if we need ajax service, we will need to create wcf services on server side to serve ajax calls, while in MVC web application, no wcf is needed, a controller will do.

Here are two examples (GET and POST) of how to use ajax in mvc application

Http Get example: ajax consumer in view

<script type="text/javascript">
  var user = {
                'id': 1
            };
    $.get(
                'home/getUser',
                user,
                function (data) {
                    alert(data.name);
                }
    );
</script>


Http Get example: ajax server in home controller

public class HomeController : Controller
{
    // data GET service
     public JsonResult getUser(int id)
     {
            User user = db.Users.where(u=>u.id==id)
            return Json(user,JsonRequestBehavior.AllowGet);     }
}

A few points:


Controller must return JsonResult rather than ActionResult as a normal controller does as we would want the data to be returnd as json data, and it does not have a ‘d’ wrapper

JsonRequestBehavior.AllowGet must be set in Json()call, otherwise you will get:

500 internal server error with message like

This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet

You only need to set this parameter for GET and returning JSON array to avoid JSON hijacking, no need for POST requests.
Http POST example: ajax consumer in view


<script type="text/javascript">
var user={
            'name':’TheUser’,
            'age':30
        };
 $.post(
            'home/SaveUser',
            user,
            function (data) {
                if (data === true) {
                   alert('User is saved');
                }
                else {

                    alert('Failed to save the user');
                }
            },
            'json'
        );
</script>


Http POST example: ajax server in home controller

public class HomeController : Controller
{
    // data POST service
  [AcceptVerbs(HttpVerbs.Post)]
   public JsonResult SaveUser (string name, int age)
   {
        return Json(true);    }
}

A few points:

Have to decorate the controller with ‘POST’

Datatype in $.post in example is set to json, but it is not necessary to be so, if you just pass data in fields rather than in complex object. When it is not set to json it will use application/x-www-form-urlencoded as a way to pass data in standard post.


Summary:
In asp.net MVC you can use controller as ajax server without having to use wcf, compared with wcf, no configuration is needed

 

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

clock June 13, 2016 21:35 by author Anthony

In this article, I will integrate and setup ELMAH to asp.net MVC project. I will finish whole article in 5 different steps. ELMAH stands for Error Logging Modules and Handlers providing application wide error logging facilities. ELMAH is pluggable and easy to implement without changing single line of code. ELMAH work as interceptor of unhandled dotnet exceptions, that display over yellow screen of death. As per Author you can dynamically add ELMAH on running asp.net application without recompile or re-deploy whole application.You can download ELMAH binaries from google code or if you are using nuget then visit ELMAH nuget page.

Install

The best way to install any module to Asp.net MVC project is to use Nuget package Console. You can visit ELMAH nuget page for get latest version command.

Configure

After installing ELMAH , it will automatically update Web.Config file. If it's not so you can add following code to Web.Config file.

<configuration>
<configSections>
    <sectionGroup name="elmah">
      <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" />
      <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
      <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" />
      <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah" />
    </sectionGroup>
</configSections>

<system.web>   
    <httpModules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
    </httpModules>
</system.web>

<system.webServer>
<modules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" />
</modules>
</system.webServer>
<elmah>
    <security allowRemoteAccess="false" />
    <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="YourConnectionStringName" />
</elmah>
    <location path="elmah.axd" inheritInChildApplications="false">
    <system.web>
      <httpHandlers>
        <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
      </httpHandlers>
      <!--
      <authorization>
        <allow roles="admin" />
        <deny users="*" /> 
      </authorization>
      --> 
    </system.web>
    <system.webServer>
      <handlers>
        <add name="ELMAH" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode" />
      </handlers>
    </system.webServer>
  </location>
</configuration>
Usage Now, It's time to use and test elmah for application. Generate exception in Home Controller
public ActionResult Index()
{
   throw new Exception("This is test Exception");
          
   return View();
}


after generating exception check your elmah like http://www.example.com/elmah.axd
Here is our output

integrate-elmah-in-aspnet-mvc

integrate elmah in asp. net mvc

Security

In addition ELMAH provides seamless security feature to prevent unauthorized access. Please read our next article to make your elmah secure.

Filtering

ELMAH identify and store exceptions in different category, you can make or edit ELMAH error screen with different filters which we will discuss in our next ELMAH series.

Notification

You can setup ELMAH email notification when any exception occurs. To unable notification option you must include below code

Add ErrorMail module
<httpModules>
    <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah"/>
</httpModules>


Add SMTP Setting
<system.net>
    <mailSettings>
        <smtp deliveryMethod="network">
            <network host="..." port="25" userName="..." password="..." />
        </smtp>
    </mailSettings>
</system.net>
 

or
<elmah>
<errorMail from="..." to="..."  async="true" smtpServer="..." smtpPort="25" userName="..." password="..." />
</elmah>

 

 


HostForLIFE.eu ASP.NET MVC 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 Hosting - HostForLIFE.eu :: How To Make Simple Application In ASP.NET MVC Using Select2?

clock June 6, 2016 23:46 by author Anthony

In this tutorial, I will show you how to make simple application in ASP.NET MVC using Select2. The infinite scrolling feature has also been implemented with server side options population. Select2 is very useful for dropdown lists with large datasets.

Why Select2 :

  • Using this jQuery plugin for dropdown lists, you can implement features such as option grouping, searching, infinite scrolling, tagging, remote data sets and other highly used features.
  • To use select2 in web projects, you just have to include JavaScript and CSS files of Select2 in your website.
  • Current version of select2 is 4.0.0. You can easily include these files by installation of NuGet package ‘Select2.js’ from NuGet package manager.

Steps of Implementation:
1. Create a blank ASP.NET MVC project, and install NuGet packages Select2.js, jQuery and jQuery Unobtrusive.
2. Add one controller with the name ‘HomeController’ and add view for default method ‘Index’.
3. Create new class in Models folder ‘IndexViewModel.cs as shown below:

public class IndexViewModel
{
   [Required(ErrorMessage="Please select any option")]
   public string OptionId { get; set; }
}

4. Bind ‘Index.cshtml’ view with IndexViewModelClass as model, by adding the following line in Index view:

@model Select2InMvcProject.Models.IndexViewModel

5. In ‘Index.cshtml’, include the css and js files below:

<link href="~/Content/css/select2.css" rel="stylesheet" />
<script src="~/Scripts/jquery-2.1.4.js"></script>
<script src="~/Scripts/select2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>


6. Write the following code in the Index view for creation of select list:

@using (Html.BeginForm())
{
   <br /><br />
   @Html.DropDownListFor(n => n.OptionId, Enumerable.Empty<SelectListItem>(), new { @id = "txtOptionId", @style = "width:300px;" })
//Created selectlist with empty enumerable of SelectListItem and given //id as “txtOptionId”
   @Html.ValidationMessageFor(n => n.OptionId)
//Adds span of validation error message
   <br /><br />
<button type="submit">Submit</button>
   <br /><br />
}


7. For applying Select2 to the dropdown list created above, fetching data from server side and for infinite scroll, use the jQuery code below in Index view:

<script type="text/javascript">
   $(document).ready(function () {
       var pageSize = 20;
       var optionListUrl = '@Url.Action("GetOptionList", "Home")';
//Method which is to be called for populating options in dropdown //dynamically
       $('#txtOptionId').select2(
       {
           ajax: {
               delay: 150,
               url: optionListUrl,
               dataType: 'json',
               data: function (params) {
                   params.page = params.page || 1;
                   return {
                       searchTerm: params.term,
                       pageSize: pageSize,
                       pageNumber: params.page
                   };
               },
               processResults: function (data, params) {
                   params.page = params.page || 1;
                  return {
                       results: data.Results,
                       pagination: {
                           more: (params.page * pageSize) < data.Total
                       }
                   };
               }
           },
           placeholder: "-- Select --",
           minimumInputLength: 0,
           allowClear: true,
   });
});
</script>


8. Create new class in Models folder with name ‘Select2OptionModel’ and add the two classes below:

public class Select2OptionModel
{
       public string id { get; set; }
       public string text { get; set; }
}
public class Select2PagedResult
{
       public int Total { get; set; }
       public List<Select2OptionModel> Results { get; set; }
}


9. Create one new folder with name ‘Repository’ in the solution, and add new class in that folder with name ‘Select2Repository. The functions in this class are mentioned below:

public class Select2Repository
   {
       IQueryable<Select2OptionModel> AllOptionsList;
public Select2Repository()
{
           AllOptionsList = GetSelect2Options();
}
IQueryable<Select2OptionModel> GetSelect2Options()
                  {
                                     string cacheKey = "Select2Options";
                                     //check cache
                                     if (HttpContext.Current.Cache[cacheKey] != null)
                                     {
return (IQueryable<Select2OptionModel>)HttpContext.Current.Cache[cacheKey];
                                     }
                                     var optionList = new List<Select2OptionModel>();
                                     var optionText = "Option Number ";
                                     for (int i = 1; i < 1000; i++)
                                     {
                                     optionList.Add(new Select2OptionModel
                                     {
                                               id = i.ToString(),
                                               text = optionText + i
                                     });
                                   }
                                   var result = optionList.AsQueryable();
                                     //cache results
                                     HttpContext.Current.Cache[cacheKey] = result;
                                     return result;}
 
List<Select2OptionModel> GetPagedListOptions(string searchTerm, int pageSize, int pageNumber, out int totalSearchRecords)
                  {
                                     var allSearchedResults = GetAllSearchResults(searchTerm);
                                     totalSearchRecords = allSearchedResults.Count;
return allSearchedResults.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();
                  }
                  List<Select2OptionModel> GetAllSearchResults(string searchTerm)
                  {

                                     var resultList = new List<Select2OptionModel>();
                                      if (!string.IsNullOrEmpty(searchTerm))
resultList = AllOptionsList.Where(n => n.text.ToLower().Contains(searchTerm.ToLower())).ToList();
                                     else
                                     resultList = AllOptionsList.ToList();
                                     return resultList;
                  }
                  public Select2PagedResult GetSelect2PagedResult(string searchTerm, int pageSize, int pageNumber)
                  {
                                     var select2pagedResult = new Select2PagedResult();
                                     var totalResults = 0;
                                     select2pagedResult.Results = GetPagedListOptions(searchTerm,
pageSize, pageNumber, out totalResults);
                                     select2pagedResult.Total = totalResults;
                                     return select2pagedResult;
}
}

10.  In HomeController class, create new method as shown below:

public JsonResult GetOptionList(string searchTerm, int pageSize, int pageNumber)
{
     var select2Repository = new Select2Repository();
     var result = select2Repository.GetSelect2PagedResult(searchTerm, pageSize, pageNumber);
     return Json(result, JsonRequestBehavior.AllowGet);
}

11. Once you are done with coding, you can build and run the project. The output will be shown as below:

dropdown1.png

dropdown2.png


HostForLIFE.eu ASP.NET MVC 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 5 Hosting Germany - HostForLIFE.eu :: Prevent CSS Attack in ASP.NET MVC with ValidateInput Attribute

clock January 8, 2015 07:45 by author Peter

We realize that a Cross Site Scripting (CSS) attack is extremely basic and is an extraordinary attack for web applications. On the off chance that you are new to CSS attacks then the following article is for you.

A CSS attack is fundamentally the consequence of poor form validation, or the info script may infuse from a query string however the shots of that are less contrasted with structure acceptance. How do CSS attacks work? From the start the programmer input some HTML code into a HTML input field and the information alongside the HTML tag is spared to the database on the off chance that we didn't check the HTML data string.

Presently, when there is a need to show the information in a user interface then we will get it from the database and a honest to goodness program will parse it as HTML code. In the event that the programmer then input an ordinary HTML string then there is no issue whatsoever. At the same time it doesn't happen by and large. They may inject harmful Javascript code from an information field that may steel important data from the client's computer.

Alright, so this is about the CSS attack. What's more I am certain that you never need to permit a user to inject a HTML component through a form.

In customary Web Form applications, we utilize a form validation script(as a part of Javascript all the time) to approve user's data. At the same time the MVC library has done the job for us, we require not to accept or compose long code remotely.

Here we will perceive how to keep a CSS attack utilizing the Validateinput attribute. First, develop 1 simple model as in the following code:
public class person
{
   public string personDescription { get; set; }
}

For simplicity we have added only one attribute in the model class. Now  I will implement the controller to render the view. Let’s write the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC_5.Models;
namespace MVC_5.Controllers
{
    public class personController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public void GetPerson(person p)
        {
        }
    }
}

This is the basic individual controller and it will throw the view when the Index() activity is called. Furthermore in the structure accommodation it will call the Getperson() action. Fine, how about we execute the view to get the form data
@model MVC_5.Models.person
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        @{
            using (Html.BeginForm("GetPerson", "person"))
            {
                <input type="text" name="personDescription" /> <br />
                <input type="submit" value="Submit Form" />
            }
         } 
    </div>
</body>
</html>

And here is the Output :

 

We are putting in a HTML component alongside data. Furthermore once we click on the submit catch we will see the following picture:

Along these lines, in MVC, of course it keeps the HTML component as form data, at any rate we can utilize the Validateinput attribute to prevent HTML explicitly in this way.
public class personController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
    [ValidateInput(true)]
    public void GetPerson(person p)
    {
    }
}


Or we can use the ValidateInput() attribute over the controller.
[ValidateInput(true)]
public class personController : Controller
{
}


If you want to allow a HTML element through form input, we can just set the true parameter to false. Then it will allow acceptance of a HTML element as input. Or
We can use the AllowHtml() attribute of the model property. On the below code, is to allow a HTML element to a certain property only.
public class person
{
    [AllowHtml]
    public string personDescription { get; set; }

}



ASP.NET MVC 5 Hosting UK - HostForLIFE.eu :: Create jQuery Accordion in ASP.NET MVC

clock December 18, 2014 10:14 by author Peter

At this moment, I am going to explain about create jQuery Accordion in ASP.NET MVC 5. This  is very simple and easy to develop a jQuery accordion in ASP.NET MVC. If we need to implement any jQuery UI widgets in ASP.NET MVC there there is no need to do any extra work. This is a cool feature of ASP.NET MVC.

And this is the example with ASP.NET MVC 5 Apps:
1. Create a blank ASP.NET MVC application.
2. Download the jQuery and jQuery UI libray fron Nuget Package Manager in the apps.
3. Create the Home Controller with this code:
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
  namespace MvcApplication8.Controllers 

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

}

4.  Make the Index view and implement the jQuery and style sheet as in this code snippet.
   @{ 
        ViewBag.Title = "Index"; 
   }        
    <script src="~/Scripts/jquery-2.1.1.min.js"></script> 
    <script src="~/Scripts/jquery-ui-1.11.2.min.js"></script> 
    <link href="~/Content/themes/base/all.css" rel="stylesheet" /> 
    <link href="~/Content/themes/base/accordion.css" rel="stylesheet" /> 
    <link href="~/Content/demos.css" rel="stylesheet" /> 
          <script type="text/javascript">         
 $(function () { 
           $("#accordion").accordion(); 
       }); 
    </script> 
      <div class="demo"> 
    <div id="accordion"> 
      <h3>This is the Title1</h3> 
      <div> 
        <p> 
        This is sample text
        </p> 
      </div> 
      <h3>This is the Title2</h3> 
      <div> 
        <p> 
       This is sample text
        </p> 
      </div>          
    </div>     
</div>



ASP.NET MVC 5 Hosting Spain - HostForLIFE.eu :: Create a Simple API in ASP.NET MVC

clock December 9, 2014 08:34 by author Peter

On this tutorial, I will show you how to create a simple API in ASP.NET MVC 5 that could return both collection of movies or one movie in Json format naturally, but depends on browser outcomes could be displayed in XML format. I targeted only on GET method during this tutorial.

1. Let’s make a new ASP.MVC apps in Visual Studio.
2. In models create interface IMoviesRepository, class Movie and MoviesRepository.

public interface IMoviesRepository
    {
        IQueryable<Movie> GetAll();
        Movie GetById(int id);
        Movie Add(Movie movie);
        bool Edit(Movie movie);
        bool Remove(Guid? id);
    }
public class Movie
    {
        public int movieId { get; set; }
        public string name { get; set; }
        public string releaseYear { get; set; }
    }
public class MovieRepository : IMoviesRepository
    {
        private List<Movie> _listOfMovies = new List<Movie>();
        public MovieRepository()
        {
            _listOfMovies.Add(new Movie {
                movieId = 1,
                name = "Keyboard massacre",
                releaseYear = "1999" });
            _listOfMovies.Add(new Movie {
                movieId = 2,
                name = "Keyboard massacre 2",
                releaseYear = "2000" });
            _listOfMovies.Add(new Movie {
                movieId = 3,
                name = "Keyboard massacre 3 ",
                releaseYear = "2001" });
        }
        public IQueryable<Movie> GetAll()
        {
            return _listOfMovies.AsQueryable();
        }
        public Movie GetById(int id)
        {
            return _listOfMovies.Find(m => m.movieId == id);
        }
        public Movie Add(Movie movie)
        {
            throw new NotImplementedException();
        }
        public bool Edit(Movie movie)
        {
            throw new NotImplementedException();
        }
        public bool Remove(Guid? id)
        {
            throw new NotImplementedException();
        }
    }

Create interface first after which MovieRepository that could inherit IMoviesRepository and merely correct click on class name and apply Implement Interface.

3. Then create new folder to your main project WebApiControllers and create Api Controller.Call itMoviesController.cs.

And here is the code for your controller class:
MovieRepository movieRepository;
        public MoviesController()
       {
            this.movieRepository = new MovieRepository();
        }

Calling default constructor can ensure that all repositories are set up. It's great practice to call all services that could be needed for controller - we're ensuring which our application is loose coupled. If you're acquainted with dependency injection this is very typical concept.

As I described I will be able to concentrate only on GET method, thus replace each GET methods along with custom code. You controller ought to such as this :
public class MoviesController : ApiController
    {
        MovieRepository movieRepository; 
        public MoviesController()        
{
            this.movieRepository = new MovieRepository();
        } 
        // GET api/movies
        public IQueryable<Movie> Get()
        {
            return movieRepository.GetAll();
        } 
        // GET api/movies/5
        public Movie Get(int id)
        {
            return movieRepository.GetById(id);
        }
        // POST api/movies
        public void Post([FromBody]string value)
        {
        } 
        // PUT api/movies/5
        public void Put(int id, [FromBody]string value)
        {
        }
        // DELETE api/movies/5
        public void Delete(int id)
        {
        }
    }

4. Run your application now and call localhost:YourPortNumber/api/movies
You should get this results in Chrome:

If you run it in IE you will be asked to save file. With opening it in notepad you will get this JSON results
[{"movieId":1,"name":"Keyboard massacre","releaseYear":"1999"},{"movieId":2,"name":"Keyboard massacre 2","releaseYear":"2000"},{"movieId":3,"name":"Keyboard massacre 3 ","releaseYear":"2001"}]

5. And this code below will improve GetById method. If movie can’t be found we want to return HttpResponseException.
// GET api/movies/5
        public Movie Get(int id)
        {
            var movie = movieRepository.GetById(id);
            if (movie == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
           }
           return movie;
        }



ASP.NET MVC 5 Hosting France - HostForLIFE.eu :: Develop a Custom HTML Helpers in ASP.NET MVC

clock December 5, 2014 07:06 by author Peter

With this article, I want to tell you about develop custom a HTML Helpers, thus that many of us could use inside the MVC 5 views, utilizing HTML Helpers class we will decrease the massive level of typing of HTML tags.

HTML Helpers
A HTML Helper is simply a method which returns a string. The string can represent any kinds of content that you need. As an example, you are able to use HTML Helpers to render standard HTML tags such as HTML <input> and <img> tags. You can also use HTML Helpers to render a lot of complicated content such as a tab strip or an HTML table of database data.

The listed are many of the standard HTML Helpers currently added in ASP. NET MVC :
Html.ActionLink()
Html.BeginForm()
Html.CheckBox()
Html.DropDownList()
Html.EndForm()
Html.Hidden()
Html.ListBox()
Html.Password()
Html.RadioButton()
Html.TextArea()
Html.TextBox()

Develop a HTML Helpers with Static Methods
The easiest method to develop a new HTML Helper is to make a static method that returns a string. For example, that you decide to create some new HTML Helpers that render an HTML <Image> tag, HTML <ActionLink> tag, HTML <ActionLinkSortable> tag, HTML <DisplayAddress> tag and HTML < label> tag. And here is the example code that I used:
public static class HtmlHelpers  
{  
     /// <summary> 
     /// Creates an Html helper for an Image 
     /// </summary>  
     /// <param name="helper"></param>  
     /// <param name="src"></param>  
     /// <param name="altText"></param>  
     /// <returns></returns>     
     public static MvcHtmlString Image(this HtmlHelper helper, string src, string altText)  
     {  
         var builder = new TagBuilder("img");  
         builder.MergeAttribute("src", src);  
         builder.MergeAttribute("alt", altText);  
         return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));  
     }     
     //create an action link that can display html     
     public static MvcHtmlString ActionLinkHtml(this AjaxHelper ajaxHelper, string linkText, string actionName,  
 string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)  
     {  
         var repID = Guid.NewGuid().ToString();  
         var lnk = ajaxHelper.ActionLink(repID, actionName, controllerName, routeValues, ajaxOptions, htmlAttributes);  
         return MvcHtmlString.Create(lnk.ToString().Replace(repID, linkText));  
     }     
     //create an action link that can be clicked to sort and has a sorting icon (this is meant to be used to create column headers)  
     public static MvcHtmlString ActionLinkSortable(this HtmlHelper helper, string linkText, string actionName,  
 string sortField, string currentSort, object currentDesc)  
     {  
         bool desc = (currentDesc == null) ? false : Convert.ToBoolean(currentDesc);  
         //get link route values  
         var routeValues = new System.Web.Routing.RouteValueDictionary();  
         routeValues.Add("id", sortField);  
         routeValues.Add("desc", (currentSort == sortField) && !desc);  
         //build the tag  
         if (currentSort == sortField) linkText = string.Format("{0} <span class='badge'><span class='glyphicon glyphicon-sort-by-attributes{1}'></span></span>", linkText, (desc) ? "-alt" : "");
TagBuilder tagBuilder = new TagBuilder("a");  
         tagBuilder.InnerHtml = linkText;  
         //add url to the link  
         var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);  
         var url = urlHelper.Action(actionName, routeValues);  
         tagBuilder.MergeAttribute("href", url);  
         //put it all together  
         return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));  
     }     
     //custom html helper to output a nicely-formatted address element     
     public static MvcHtmlString DisplayAddressFor<TModel, TProperty>(this HtmlHelper<TModel> helper, 
 System.Linq.Expressions.Expression<Func<TModel, TProperty>> expression, bool isEditable = false,   object htmlAttributes = null)  
   {  
        var valueGetter = expression.Compile();  
        var model = valueGetter(helper.ViewData.Model) as InGaugeService.Address;  
        var sb = new List<string>();  
        if (model != null)  
       {  
             if (!string.IsNullOrEmpty(model.AddressLine1)) sb.Add(model.AddressLine1);  
             if (!string.IsNullOrEmpty(model.AddressLine2)) sb.Add(model.AddressLine2);  
             if (!string.IsNullOrEmpty(model.AddressLine3)) sb.Add(model.AddressLine3);  
             if (!string.IsNullOrEmpty(model.City) || !string.IsNullOrEmpty(model.StateRegion) ||   !string.IsNullOrEmpty(model.PostalCode)) sb.Add(string.Format("{0}, {1} {2}", model.City,  model.StateRegion, model.PostalCode));  
             if (model.IsoCountry != null) sb.Add(model.IsoCountry.CountryName);  
             if (model.Latitude != null || model.Longitude != null) sb.Add(string.Format("{0}, {1}",   model.Latitude, model.Longitude));  
         }     
         var delimeter = (isEditable) ? Environment.NewLine : "<br />";  
         var addr = (isEditable) ? new TagBuilder("textarea") : new TagBuilder("address");            addr.MergeAttributes(new System.Web.Routing.RouteValueDictionary(htmlAttributes));        addr.InnerHtml = string.Join(delimeter, sb.ToArray());  
        return MvcHtmlString.Create(addr.ToString());  
     }  
     public static string Label(string target, string text)  
     {  
        return String.Format("<label for='{0}'>{1}</label>", target, text);  
     }     
     //Submit Button Helper  
     public static MvcHtmlString SubmitButton(this HtmlHelper helper, string buttonText)       
{  
         string str = "<input type=\"submit\" value=\"" + buttonText + "\" />";  
         return new MvcHtmlString(str);  
     } 
 } 



ASP.NET MVC 5 Hosting Germany - HostForLIFE.eu :: How to use jQuery UI in ASP.NET MVC 5 ?

clock December 2, 2014 10:25 by author Peter

Several developers struggle to work along with jQuery UI inside an ASP.NET MVC 5 application. During this publish, I will be able to show you 3 actions needed to begin dealing with jQuery UI inside an ASP.NET MVC application. In the end from the publish we'll check out working with the autocomplete widget. On the listed 3 steps that could allow you perform along with jQuery UI inside an ASP.NET MVC Apps:

1. Add the jQuery UI Reference
Add the jQuery UI reference straight into the project by using the NuGet manager. Once this is done, you ought to discover the reference additional inside the Content folder and also the Scripts folder.

2. Bundle the needed files
Open up the BundleConfig.cs file. In this file add 2 entries, one to the jQuery UI scripts along with other for jQuery UI CSS. Add the script entry as follows :
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
            "~/Scripts/jquery-ui-{version}.js"));

Next add the CSS files for jQueryUI widgets. CSS for all those the widgets could be bundled such as this:
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
              "~/Content/themes/base/jquery.ui.core.css",
              "~/Content/themes/base/jquery.ui.resizable.css",
              "~/Content/themes/base/jquery.ui.selectable.css",
              "~/Content/themes/base/jquery.ui.accordion.css",
              "~/Content/themes/base/jquery.ui.autocomplete.css",
              "~/Content/themes/base/jquery.ui.button.css",
              "~/Content/themes/base/jquery.ui.dialog.css",
              "~/Content/themes/base/jquery.ui.slider.css",
              "~/Content/themes/base/jquery.ui.tabs.css",
              "~/Content/themes/base/jquery.ui.datepicker.css",
              "~/Content/themes/base/jquery.ui.progressbar.css",
              "~/Content/themes/base/jquery.ui.theme.css"));


For the purpose of the example, let’s say you're solely dealing with the autocomplete widget. During this case, you'd just bundle the core. css and autocomplete. css as shown beneath:
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
              "~/Content/themes/base/jquery.ui.core.css",            
              "~/Content/themes/base/jquery.ui.autocomplete.css",             
              "~/Content/themes/base/jquery.ui.theme.css"));

3. Refer towards the Bundles
Once the bundles for jQuery UI happen to be produced, you have to add them to be able to the layout file. That may be done as follows:
    @Styles.Render("~/Content/css")
    @Styles.Render("~/Content/themes/base/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @Scripts.Render("~/bundles/jqueryui")


Obviously you will see the jQuery bundle at the end from the layout file. To work along with jQuery UI widgets, you ought to transfer the jQuery bundle to the top of the file and likewise include the bundles for jQuery UI CSS and Scripts.

You've currently completed the 3 steps needed to work along with jQueryUI inside an ASP. NET MVC application.

Use jQueryUI Widgets
Now let’s look into the autocomplete widget in action. I've developed a controller for returning JSON data as follows:
public ActionResult Index()
        {
                     return View();
        }
        public ActionResult GetMP(string term)
        {
            var result = from r in _db.GetMPDetails()
                         where r.Name.ToLower().Contains(term)
                         select r.Name;           
            return Json(result, JsonRequestBehavior.AllowGet);
        }


We'll currently bind the returned JSON coming from the GetMP () motion towards the autocomplete widget. Upon the razor view, you are able to create an autocomplete widget such as this:
<input type="text" id="mpvalue" name="mpvalue" /> 
<script type="text/javascript">
    $(document).ready(function () { 
        $('#mpvalue').autocomplete({
            source: '@Url.Action("GetMP")'
        }); 
    })
</script>


Be certain the view is using the layout file in which you added the reference from the bundles.



ASP.NET MVC 5 Hosting UK - HostForLIFE.eu :: Using the ASP.NET MVC 5 Filter Overrides Feature

clock October 28, 2014 09:04 by author Peter

In the previous post we took a glance at the new authentication filter and its strong points. There's an extra new filter that has been free with ASP.NET MVC 5 Hosting that was requested by several developers out their over a protracted time. This can be the new filter override feature! Within the previous versions of MVC, there was no thanks to override a filter for simply one action or controller. What you had to do is to use the filter for every and each action and controller one by one and this was an enormous waste of development time. Rather than doing this developers found ways to implement filter overrides using workaround. But usually the usage of workarounds cause the lack of code consistency. Therefore as an answer for this, Filter Overrides feature was introduced in MVC 5.

Filter Overrides in action

Imagine a situation where you want to exclude a globally applied authorization filter just only for a single action method. This was one thing you may not implement easily with the previous versions of MVC. however now the MVC 5 Filter Overrides feature provides you this capability with few lines of code. Lets have a glance at the following code snippet:

[Authorize(Users = "Admin")]
public class HomeController : Controller
{
    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();
    }
}

As you'll see AuthorizeAttribute has been embellished to the HomeController class with the user ‘Admin’. so it applies to all or any the actions within the controller. Assume you would like to bypass this filter only for the ‘About’ action. you would like to provide access to ‘About’ page just for user ‘Peter’ only. In MVC 5 you'll achieve this by adding 2 lines of code as illustrated in the following code snip.

 

OK. That’s it. currently all the actions inside the home Controller will only be accessed by ‘Admin’ except the ‘About’ action. The ‘About’ action is merely accessible for ‘Peter’. therefore now you'll get eliminate the headache of applying filters for every and each action wherever you would like to exclude only one or 2 actions.

There are 5 kinds of override filters accessible for every of filter types:

  1.     OverrideActionFilters
  2.     OverrideAuthentication
  3.     OverrideAuthorization
  4.     OverrideExceptionFilters
  5.     OverrideResultFilters

You will use the relevant override filters where is required.

Filter Override Bug Workaround

For making a bug workaround you'll have to do some of things:
Implement a custom class that may inherit from the action filter that you just wish to override and implement the IOverrideFilter. You’ll have to implement the FiltersToOverride property wherever you have got to identify the filters that you wish to override. for example lets create an easy workaround for the instance that has been described above:
public class MyOverrideAuthorizeAttribute : AuthorizeAttribute, IOverrideFilter
{
    public Type FiltersToOverride
    {
        get
        {
            return typeof(IAuthorizationFilter);
        }
    }
}

Then, the Controller implementation will change to:
[Authorize(Users = "Admin")]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
    [MyOverrideAuthorize(Users = "Peter")]
    public ActionResult About()
    {
        ViewBag.Message = "Your application description page.";
        return View();
    }
    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";
        return View();
    }
}



ASP.NET MVC 5 Hosting UK - HostForLIFE.eu :: How to Easily Add ASP.NET MVC Anti-Forgery Tokens to any or all Post Requests

clock October 24, 2014 07:35 by author Peter

Today, I will show you How to Easily Add ASP.NET MVC 5 Anti-Forgery Tokens to any or all Post Requests. One of the newer attacks against web applications is that the cross-site request forgery attack. It’s an attack against modern applications that store a cookie to represent the presently logged in user. The matter has been explained in different websites.

One of the techniques to stop this attack is to add an anti-forgery token using the @Html.AntiForgeryToken extension technique. On the controller side, the action technique defines the [ValidateAntiForgeryToken] attribute. Behind the scenes, the hidden input field for the anti-forgery token is valid by the ASP.NET MVC  5 framework to confirm it’s correct. Whereas there's discussion as to whether or not this approach is required only for the logging in an anonymous posts, or all posts in general, as been up for debate. However the purpose of CSRF is to attack authenticated users.
public class GlobalAntiForgeryTokenAttribute
  : FilterAttribute, IAuthorizationFilter
{
  public sub OnAuthorization(filterContext As AuthorizationContext)
  {
                if (filterContext.HttpContext.Request.HttpMethod.ToUpper() == "POST")
                {
                  AntiForgery.Validate();
    }         
  }
}

On authorization of the request, if the operation may be a POST request, we tend to call the Validate() method on the AntiForgery helper to actually perform the validation. All of our post operations are currently checked for forgery; but, this can fail as a result of we haven’t added our token globally. To do that, we've to create a custom form extension method just like the following:

public static void FormExtensions
{
   public static MvcForm BeginDataForm(this HtmlHelper html, string action, string controller, ...)
  {
     var form = html.BeginForm(action, controller, ...);
                 //At this point, the form markup is rendered in BeginForm
                 // we can render the token       
                 //With every form, we render a token, since this
                 //assumes all forms are posts
                 html.ViewContext.Writer.Write(html.AntiForgeryToken().ToHtmlString());
                return form;
   }
}

If we use our custom helper for all of our forms, then all of our custom forms can have rendered an anti-forgery token. so we don’t have to worry about making it ourselves, saving time and reducing code.



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