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 UK - HostForLIFE.eu :: Changing image opacity & Zoom on mouseover using jQuery in ASP.NET MVC

clock January 23, 2015 12:20 by author Peter

With this post, I will explain you about changing image opacity & zoom on mouseover with jQuery in ASP.NET MVC. First step, write the following code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>How to change image opacity and Zoom on mouseover using jQuery</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#imgSample").css("opacity", "0.5");
            $("#img1").hover(function () {
                $(this).css("opacity", "1.0");
                $(this).animate({ width: "400px" }, 'slow');
                $(this).animate({ height: "300px" }, 'slow');
            },
              function () {
                   $(this).css("opacity", "0.5");
                   $(this).animate({ width: "200px" }, 'slow');
                   $(this).animate({ height: "150px" }, 'slow');
               });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       <img id="imgSample" src="images/NiceImage.jpg" width="200px" height="150px" alt="img" />
        <img id="img1" src="images/NiceImage.jpg" width="200px" height="150px" alt="img" />
    </div>
    </form>
</body>
</html>

And here is the result of the code above.

The Opacity 0.5 shows like the picture below.

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 Russia :: Creating Dynamic DropdownList in ASP.NET MVC 6

clock January 22, 2015 05:54 by author Peter

With this short tutorial, I will tell you how to create dynamic DropDownList with ASP.NET MVC 6. First thing you should do is make 2 DB Tables. And here is the example:

1.Designstions
Columns: DesignationID(PK,FK,numeric(6,0),not null)
             Designation (Varchar(50),null)

2.Persons
Columns: PersonID(PK,numeric(6,0),not null)
                 DesignationID(FK,numeric(6,0),not null)


Create The Models:
Designation.cs
{
   public decimal DesignationID { get; set; }
    public string Designation { get; set; }
}


Person.cs
{
    public decimal PersonID{ get; set; }
     [DisplayName("Designation")]
   public decimal DesignationID{ get; set; }
    public virtual  Designation designation { get; set; }
}


PersonController.cs
{
  public class PersonController: Controller
{
     public ActionResult Index()
        {
            var  mamun= db.Persons.Include(t => t.designation );
            return View(mamun.ToList());
        }
 public ActionResult Create()
        {
          ViewBag.DesignstionID= new SelectList(db.Designstions, "DesignstionID", "Designstion");
            return View();
        }
  public ActionResult Edit(decimal id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Person person = db.Persons.Find(id);
            if (tblsalesperson == null)
            {
                return HttpNotFound();
            }
         ViewBag.DesignstionID= new SelectList(db.Designstions, "DesignstionID", "Designstion",person.DesignstionID);
                   return View(person);
        }
}
}

Next step, create.cshtml & Edit.cshtml:
<div class="form-group">
                @Html.Label("Designation", new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownList("DesignstionID")
                    @Html.ValidationMessageFor(model => model.DesignstionID)
                </div>
            </div>

I am using this following code to Add CSS class  'dropdownList' :
@Html.DropDownList("DesignstionID", (IEnumerable<SelectListItem>)ViewBag.DesignstionID, new { @class = "dropdownList" })  Instead Of that.

Index:  
@foreach (var item in Model)
{
    <td>
                    @Html.DisplayFor(modelItem => item.Designation.Designation)     
  </td>
}

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 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; }

}



HostForLIFE.eu Proudly Launches DotNetNuke 7.3.4 Hosting

clock December 23, 2014 07:32 by author Peter

European leading web hosting provider, HostForLIFE.eu announced support for DotNetNuke 7.3.4 hosting plan due to high demand of DotNetNuke CMS users in Europe.

HostForLIFE.eu proudly launches the support of DotNetNuke 7.3.4 on all our newest Windows Server  environment. HostForLIFE.eu DotNetNuke 7.3.4 Hosting plan starts from just as low as €3.00/month only and this plan has supported ASP.NET 5, ASP.NET MVC 5/6 and SQL Server 2012/2014.

DotNetNuke 7.3.4, as well known in the web industry and familiar among .NET developers, is a Web Content Management System (WCMS) based on Microsoft .NET platform. It is an excellent open source software that you can use to manage your website without having much technical knowledge.

HostForLIFE.eu clients are specialized in providing supports for DotNetNuke for many years. We are glad to provide support for European DotNetNuke 7.3.4 hosting users with advices and troubleshooting for our clients website when necessary.

DNN 7.3.4 is a smaller maintenance release than normal and is focused on addressing the most serious platform issues. DNN 7.3.4 addresses a number of platform issues and should be the last release before DNN 7.4.0. DNN 7.3.4 added ability to save localized lists to resource file, added method to remove all subscriptions from a ContentItem, fixed issue where AUM was not correctly handling 301 redirects, Fixed issue where popup iframe is not initialized correctly and fixed issue where multiple region/country controls in a profile did not work correctly.

DotNetNuke 7.3.4 will be a great content management system that support many advance website features such as blogs, forums, e-commerce system, photo galleries and more. DotNetNuke 7.3.4 is a great platform to build your web presence with. HostForLIFE.eu can help customize any web software that company wishes to utilize.

Further information and the full range of features DotNetNuke 7.3.4 Hosting can be viewed here http://www.hostforlife.eu/European-DotNetNuke-734-Hosting

About Company
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. HostForLIFE.eu deliver on-demand hosting solutions including shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see http://www.asp.net/hosting/hostingprovider/details/953). Our service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries.

 



ASP.NET MVC 6 Hosting Germany - HostForLIFE.eu :: How to Create Random Authorization code in c# in ASP.NET MVC ?

clock December 19, 2014 06:19 by author Peter

Now, with this article I am going to create random 15 characters long authorization number in ASP.NET MVC 6. This can be used for several completely different purposes in your MVC application like unique barcodes, authorization codes etc. to make thinks more fascinating we are getting to force the method to place letter before and after random code. GenerateLetter method is responsible to provide us only letter. I used this code based on small tutorial.

Controller
public char GenerateLetter()
        {
            Random randomNumber = new Random();
            int number = randomNumber.Next(0, 26);
            char letter = (char)('a' + number);
            return letter;
        }
        public string GenerateAuthCode()
        {
            bool codeExists = false;
            string code = GenerateLetter().ToString();
            do
            {
                code += Guid.NewGuid().ToString("N").Substring(0, 13);
                code += GenerateLetter().ToString();
                YourDBContext dbContext = new YourDBContext();
var Exists = dbContext.products.FirstOrDefault(m => m.barcode ==   code);
                codeExists = Exists == null? false : true;
            }
            while (codeExists);               
            return code;       
        }

I am calling GenerateLetter method twice before & after random 13 characters code is generated. I also want to make sure that code is always unique so I am calling Database to find if any product already have this barcode, if so my method will repeat whole process.



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>



HostForLIFE.eu Proudly Launches of WordPress 4.0.1 Hosting

clock December 15, 2014 10:11 by author Peter

European leading web hosting provider, HostForLIFE.eu announced the support for WordPress 4.0.1 hosting plan due to high demand of WordPress 4.0.1 users in Europe. HostForLIFE.eu is a popular online WordPress hosting service provider catering to those people who face such issues. The company has managed to build a strong client base in a very short period of time. It is known for offering fast, fully-managed and secured services in the competitive market.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam (NL), London (UK), Paris (France) and Seattle (US) to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security, and fire suppression. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee. The customer can start hosting our Wordpress 4.0.1 site on our environment from as just low €3.00/month only.

WordPress 4.0.1 patches a critical cross-site scripting vulnerability affecting comment boxes on websites running the content management system software. An attacker would need only to inject malicious JavaScript into a comment that would infect a reader viewing it on the webpage or an admin in the management dashboard.

The update also addresses three other cross-site scripting vulnerabilities, a cross-side request forgery flaw, a denial-of-service bug related to password checks, server-side request forgery issues, and what WordPress called “an extremely unlikely hash collision” that could lead to account compromise. WordPress said it also invalidates links in a password reset email if the user remembers our password and logs in and changes our email address.

WordPress 4.0.1 addresses an additional eight security issues, including three other XSS vulnerabilities that can be exploited by a contributor or an author, a cross-site request forgery (CSRF) that can be leveraged to trick a user into changing his/her password, and a denial-of-service (DoS) bug. HostForLIFE.eu is a popular online Windows based hosting service provider catering to those people who face such issues. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market. Our powerful servers are specially optimized and ensure WordPress 4.0.1 performance.

For more information about this new product, please visit http://hostforlife.eu/European-WordPress-401-Hosting

About us:
HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see http://www.asp.net/hosting/hostingprovider/details/953). Our service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, we have also won several awards from reputable organizations in the hosting industry and the detail can be found on our official website.



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;
        }



HostForLIFE.eu Proudly Launches ASP.NET 5 Hosting

clock December 8, 2014 10:14 by author Peter

European leading web hosting provider, HostForLIFE.eu announces the launch of ASP.NET 5  support on the recently released Windows Server 2012.

HostForLIFE.eu was established to cater to an under served market in the hosting industry; web hosting for customers who want excellent service. HostForLIFE.eu – a cheap, constant uptime, excellent customer service, quality, and also reliable hosting provider in advanced Windows and ASP.NET technology. HostForLIFE.eu proudly announces the availability of the ASP.NET 5 hosting in our entire servers environment.

ASP.NET is Microsoft's dynamic website technology, enabling developers to create data-driven websites using the .NET platform and the latest version is 5 with lots of awesome features. ASP.NET 5 is a lean .NET stack for building modern web apps. Microsoft built it from the ground up to provide an optimized development framework for apps that are either deployed to the cloud or run on-premises. It consists of modular components with minimal overhead.

According to Microsoft officials, much of the functionality in the ASP.NET 5 release is a new flexible and cross-platform runtime, a new modular HTTP request pipeline, Cloud-ready environment configuration, Unified programming model that combines MVC, Web API, and Web Pages, Ability to see changes without re-building the project, etc.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam (NL), London (UK), Paris (FR) and Seattle (US) to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security, and fire suppression. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee. The customers can start hosting our ASP.NET 5 site on our environment from as just low €3.00/month only.

HostForLIFE.eu is a popular online ASP.NET  based hosting service provider catering to those people who face such issues. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market.

HostForLIFE.eu offers the latest European ASP.NET 5 hosting installation to all our new and existing customers. The customers can simply deploy our ASP.NET 5 website via our world-class Control Panel or conventional FTP tool. HostForLIFE.eu is happy to be offering the most up to date Microsoft services and always had a great appreciation for the products that Microsoft offers.

Further information and the full range of features ASP.NET 5 Hosting can be viewed here http://www.hostforlife.eu

About Company
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. HostForLIFE.eu deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see http://www.asp.net/hosting/hostingprovider/details/953). Their service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, we have also won several awards from reputable organizations in the hosting industry and the detail can be found on our official website.



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);  
     } 
 } 



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