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 Netherlands - How to Clean up Controller Class in ASP.NET MVC?

clock January 30, 2015 06:12 by author Peter

In this article, I will tell you about How to Clean up Controller Class in ASP.NET MVC 6.  Here may be a tiny piece and the way i use some easy tricks to assist clean up my Controllers in ASP.NET MVC.

public class MyController : Controller
{
    public MyEntities Db { get; set; }
    protected override void OnActionExecuting(
        ActionExecutingContext filterContext)
    {
        if (filterContext.IsChildAction)
            return;
        this.Db = new MyEntities();
        base.OnActionExecuting(filterContext);
    }
    [HttpPost]
    public ActionResult Index(FormCollection form)
    {
        string srch = form["Search"] ?? string.Empty;
        return RedirectToAction("Index",
            new { search = srch });
    }
    protected void AttachToDb(EntityObject obj,
        bool save = false, string entityKeyField = "Id")
    {
            obj.EntityKey = new EntityKey(
                obj.ToPluralizedString(), entityKeyField,
                obj.GetType().GetProperty("Id")
                .GetValue(obj, null));
            Db.Attach(obj);
            Db.ObjectStateManager.ChangeObjectState(
                obj, System.Data.EntityState.Modified);
            if (save) Db.SaveChanges();
    }
}


The first issue within the code is easy declaration of an EntityContext - this can be enforced directly, however might (and sometimes should) be implemented differently for dependency injection, however you get the thought. Here is wherever I conjointly prefer to include stuff that's typically used and will be very important (and centralized) for an application like an output sort for web services (JSON, XML, etc.).

Next the OnActionExecuting is over-ridden and also the Context is initialized. Here is wherever you'll be able to initialize the properties you set above.

The next methodology, the HttpPost Index method is simply an example of however often times you'll be able to consolidate a normally used method. For this instance, it absolutely was from an application that had searches on all index pages. Rather than repeating this code in each controller, you'll be able to simply place it here.

The final methodology has become terribly helpful. A use I often realize, is when taking in a large model when an ASP.NET MVC POST event, I will attach the model to the db generically with none further work

This method may be a bit confusing, however it's merely attaching the new model to the db while not a db lookup. In my tables, I typically have a field 'Id' that houses the primary Key of every table, whether or not it's an Int or Guid. This way, I will merely pass in whatever object i'm currently working with, and by using the pluralize method, and reflection, the method will find out that table to connect the model to - eliminating the requirement on behalf of me to try and do extra writing. or else, if i need to change the Key from 'Id', I will pass that in as well.

Now once I get a model being posted, it's simple to deal with:
[HttpPost]
public ActionResult Edit(Widget model)
{
    if(ModelState.IsValid)
    {
        AttachToDb(model, true);
        //do stuff
    }
    else { /*do other stuff*/ }
}


This avoids the need to take another trip to the db, change the properties on the object, then submit - streamlining the method very much and lowering plenty of code. This would be an example of however this is able to be done manually with the normal Controller class:

[HttpPost]
public ActionResult Edit(Widget model)
{
    if(ModelState.IsValid)
    {
        MyEntities db = new MyEntities();
        Widget w = db.Widgets.Single(x => x.Id == model.Id);
        w.Name = model.Name;
        w.Serial = model.Serial;
        db.SaveChanges();
        //do stuff
    }
    else { /*do other stuff*/ }
}

Not a large difference once you are simply getting a pair of values, however you may see how a model with twenty or thirty fields are often block from 30+ lines to just 1 or 2.

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 Get the Values from HTTP Query String Variables in View in ASP.NET MVC 6 ?

clock January 29, 2015 07:21 by author Peter

This method can be utilized as a part of any perspective however it is prescribed to verify your ViewModel contains all essential data. We are going to utilize this methodology as a part of design page, as regularly layout page does not have any model(it can have however then it may get exceptionally muddled and by and by I think for enormous tasks it could be extra constraint).

Consider a circumstance in which you are occupied with values for variables from HTTP request.
http://localhost:49853/Home/Index?searchType=global

In above address we are passing variable searchType. How about we accept that searchType. can have 2 separate values - local and global.
Main CSS file:
#mainNav.global {
  background: #404939; }
  #mainNav.global nav.nav {
    background: none; }
    #mainNav.global nav.nav .top {
      background: #404939; }
    #mainNav.global nav.nav a:hover, #mainNav nav.nav a.active {
      background-color: #7dc243; }     
      #mainNav.local
      {
          background: #3C7987; }
        #mainNav.localnav.nav {
                  background: none; }
        #mainNav.local nav.nav .top {
                          background: #3C7987; }
        #mainNav.local nav.nav a:hover, #mainNav nav.nav a.active {
                        background-color: #7FDCFF; }


In layout page in _Layout file header section:
<header>
        <div class="content-wrapper">
            <div class="float-left">
                <p class="site-title">@Html.ActionLink("your logo here", "Index", "Home")</p>
            </div>
            <div class="float-right">
                <section id="login">
                    @Html.Partial("_LoginPartial")
                </section>
                @{
                    string searchClass = "global";
                    if (HttpContext.Current.Request.Params["searchType"] == "local")
                    {
                        searchClass = "local";
                    }
                }
                <div id="mainNav" class=@searchClass>
                    <nav class="nav" data-nav>
                        <ul>
                  @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "searchForm" }))
                            {
                                @Html.ActionLink("Global","Index","Home", new { searchType= "global" }, null)
                                @Html.ActionLink("Local","Index", "Home", new { searchType = "local" }, null)
                                <input type="search" name="searchMode" value="" placeholder="Search...">
                                <input type="submit" name="submitBtn" value="Search">
                            }
                        </ul>
                    </nav>
                </div>
               <nav>
                    <ul id="menu">
                        <li>@Html.ActionLink("Home", "Index", "Home")</li>
                        <li>@Html.ActionLink("About", "About", "Home")</li>
                        <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    </ul>
               </nav>
            </div>
        </div>
    </header>

Now, we aregoing to toggle class name for navigation bar. If we are in global searchType background color is #7dc243, in local searchType 7FDCFF.

If you are in global searchType your address is :
http://localhost:49853/?searchType=global

In local :
http://localhost:49853/?searchType=local

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.



HostForLIFE.eu Proudly Launches Sitefinity 7.3 Hosting

clock January 26, 2015 10:13 by author Peter

HostForLIFE.eu, a leading web hosting provider, has leveraged its gold partner status with Microsoft to launch its latest Sitefinity 7.3 Hosting support.

European Recommended Windows and ASP.NET Spotlight Hosting Partner in Europe, HostForLIFE.eu, has announced the availability of new hosting plans that are optimized for the latest update of the Sitefinity 7.3 hosting technology.

HostForLIFE.eu supports Sitefinity 7.3 hosting on our latest Windows Server and this service is available to all our new and existing customers. Sitefinity 7.3 offers a natural extension to all customer SharePoint workflows and wrap a compelling presentation around client core business documents. Contextual task-oriented approach to organizing documentation on any topic.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam, London, Paris 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 Sitefinity 7.3  site on our environment from as just low €3.00/month only.

Sitefinity 7.3 is a Web Content and Experience Management Platform that enables business to engage, convert and retain customers through multiple channels. Sitefinity 7.3 is the only truly mobile web content management on the market that supports all three mobile strategies out of the box – responsive design, mobile apps and mobile sites.

Sitefinity 7.3’s intuitive user interface delights both developers and business users alike, making it a more efficient environment to get more work done faster. There’s no long training required, so even new non-technical users will be up and running in no time. Because it’s built on a modern code-base, Sitefinity is best equipped to meet the long term needs of today’s expanding businesses, including tackling challenges like mobile, ecommerce, multisite management, content personalization, and so much more.

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 Sitefinity 7.3 performance.

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

About HostForLIFE.eu :
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 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; }

}



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