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

European ASP.NET MVC 3 Hosting :: Configurable Action Filter Provider in ASP.NET MVC 3

clock August 23, 2011 04:49 by author Scott

In MVC 3 you can implement an IFilterProvider to create and feed action filters to the MVC runtime. Assuming you have the configuration classes in place from the last post, you can create a custom filter provider to add action filters to the MVC pipeline. 

public class ConfiguredFilterProvider : IfilterProvider
{
    public IEnumerable<Filter> GetFilters(
        ControllerContext controllerContext,
        ActionDescriptor actionDescriptor)
    {
        var filters = FiltersSettings.Settings.Filters;
        foreach (var filter in filters.Cast<FilterAction>())
        {
            var filterType = Type.GetType(filter.Type);
            yield return new Filter(
                    Activator.CreateInstance(filterType),
                    FilterScope.Global, order:null         
                );
        }
    }
}

Notice a filter provider receives context parameters it can use to determine if it should create a filter, or not. In this case we are creating global filters from whatever we find in the web.config file, so the parameters are left untouched.

To plug your filter provider into the MVC runtime, you'll need to execute a bit of code during application start up:

FilterProviders.Providers.Add(new ConfiguredFilterProvider());



European ASP.NET MVC 3 Hosting :: Configurable Global Action Filters for ASP.NET MVC 3

clock August 22, 2011 06:13 by author Scott

ASP.NET MVC 3.0 introduces global action filters - an easy way to apply an action filter to every action in an MVC application. All you need to do is register the filters during application startup:

protected void Application_Start()
{
    ...

    GlobalFilters.Filters.Add(new HandleErrorAttribute());
    GlobalFilters.Filters.Add(new FooFilter());
    GlobalFilters.Filters.Add(new BarFilter());
    ...
}

But what if you wanted to add (or remove) filters through configuration?

<configSections>
  <section name="filters"
           type="ConfigurableFilters.FiltersSettings, AssemblyName "/>
</configSections>
...
<filters>
  <add type="System.Web.Mvc.HandleErrorAttribute, System.Web.Mvc..." />
  <add type="ConfigurableFilters.BarFilter, AssemblyName" />
  <add type="ConfigurableFilters.FooFilter, AssemblyName" />
</filters>

In that case you'll need a ConfigurationElement.

public class FilterAction : ConfigurationElement
{
    [ConfigurationProperty("type", IsRequired = true, IsKey = true)]
    public string Type
    {
        get { return base["type"] as string; }
        set { base["type"] = value; }
    }
}

And a ConfigurationElementCollection.

public class FilterActionCollection : ConfigurationElementCollection
{      
    protected override ConfigurationElement CreateNewElement()
    {
        return new FilterAction();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {           
        return ((FilterAction) element).Type;
    }
}

And a ConfigurationSection

public class FiltersSettings : ConfigurationSection
{
    public static FiltersSettings Settings
    {
        get
        {
            var section = ConfigurationManager.GetSection("filters")
                          as FiltersSettings;
            return section ?? new FiltersSettings();               
        }
    }

    [ConfigurationProperty("", IsDefaultCollection = true)]
    public FilterActionCollection Filters
    {
        get
        {
            return base[_filtersProperty] as FilterActionCollection;
        }
        set
        {
            base[_filtersProperty] = value;
        }
    }

    private readonly ConfigurationProperty _filtersProperty =
        new ConfigurationProperty(
            null, typeof (FilterActionCollection), null,
            ConfigurationPropertyOptions.IsDefaultCollection);
}

One way to apply the configured filters is to use the following code during application startup:

var filters = FiltersSettings.Settings.Filters;
foreach (var filter in filters.Cast<FilterAction>())
{
    var filterType = Type.GetType(filter.Type);
    GlobalFilters.Filters.Add(Activator.CreateInstance(filterType));
}



European ASP.NET MVC 3 Hosting :: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

clock August 10, 2011 06:44 by author Scott

MVC 3 is becoming hugely popular thanks to Razor and the Helpers that make building web applications much easier. One of the common requirements in web development, both with web forms as well as MVC based development, is the cascading dropdownlist. Now, for Web Forms, we can use a variety of options viz. server side programming, jQuery or using the AJAX Control Toolkit’s cascading dropdownlist control for accomplishing this.

I saw a few samples on the internet that used the erstwhile Microsoft AJAX Library along with MVC and also few more samples which used hard coded values for wiring up the cascading dropdown. I have built this sample using Database with 3 tables i.e. Cars, Makes & Colours.

To begin with, lets examine the Database – CascadeSample. It has 3 tables

1. Cars
2. Models
3. Colours

First, lets create our MVC 3 Application using “File – New Project – ASP.NET MVC 3 Web Application” give it a name “CascadingDropdownSample” and select the “Internet Application” and click ok. This would create the basic scaffolding structure with Membership API. We won’t need it though.

As always with MVC, lets build the Model by right click Models Folder – Add – New Item and search for ADO.NET Entity in the search box of the Dialog.

Chose the ADO.NET Entity Data Model Template and give it a name CarModel.edmx and click Add.

Choose the “Generate from Database” option and in the Next steps, connect to the CascadeSample database and select all the 3 tables and then finish the steps to generate the Entity Model. Our Entity Model is now ready.

Next step is to start wiring up the Controller Actions. For the purpose of this simple demo, lets just use the default HomeController.

Lets add using CascadingDropdownSample.Models; to the namespaces in the HomeController.

Lets add CascadeSampleEntities cse = new CascadeSampleEntities(); within the class

Lets add the following within the Index Action.

public ActionResult Index()
{

ViewBag.Cars = cse.Cars.ToList();
ViewBag.Models = cse.Models.ToList();
ViewBag.Colours = cse.Colours.ToList();
return View();
}
 


Lets switch to the View (ROOT – Views – Home – Index.cshtml) and edit it to look as follows:-

@model CascadingDropdownSample.Models.CascadeSampleEntities
@{
ViewBag.Title = "Home Page";
}

<h2>Cars</h2>
<p>
@Html.DropDownListFor(Model => Model.CarId, new SelectList(ViewBag.Cars as System.Collections.IEnumerable, "CarId", "CarName"),
"Select a Car", new { id = "ddlCars" })
</p>

When we run the page, we will get to see the List of cars in the dropdown.

For the next set of actions i.e. populating the Model and Colour, we need the following Methods.

private IList<Model> GetModels(int id)
{
return cse.Models.Where(m => m.CarId == id).ToList();
}

private IList<Colour> GetColours(int id)
{
return cse.Colours.Where(c => c.ColourId == id).ToList();
}

The next main thing we need is Action methods which can send a JSon Result for both Models and Colours.

To first get the Models by car, we add the following to the HomeController

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadModelsByCar(string id)
{
var modelList = this.GetModels(Convert.ToInt32(id));

var modelData = modelList.Select(m => new SelectListItem()
{
Text = m.ModelName,
Value = m.ModelId.ToString(),

});

return Json(modelData, JsonRequestBehavior.AllowGet);
}
 


and to get the Colours for the various Models, we add

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadColoursByModel(string id)
{
var colourList = this.GetColours(Convert.ToInt32(id));

var colourData = colourList.Select(c => new SelectListItem()
{
Text = c.ColourName,
Value = c.ColourId.ToString(),

});

return Json(colourData, JsonRequestBehavior.AllowGet);
}
 


Finally, we need to add the following jQuery handlers for the dropdownlist selection changed

<script type="text/javascript">
$(document).ready(function () {
$("#ddlCars").change(function () {
var idModel = $(this).val();
$.getJSON("/Home/LoadModelsByCar", { id: idModel },
function (carData) {
var select = $("#ddlModels");
select.empty();
select.append($('<option/>', {
value: 0,
text: "Select a Model"
}));
$.each(carData, function (index, itemData) {

select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
});
});
$("#ddlModels").change(function () {
var idColour = $(this).val();
$.getJSON("/Home/LoadColoursByModel", { id: idColour },
function (modelData) {
var select = $("#ddlColours");
select.empty();
select.append($('<option/>', {
value: 0,
text: "Select a Colour"
}));
$.each(modelData, function (index, itemData) {

select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
});
});
});

</script>

And then add the dropdowns for Model and Colour

<p>
@Html.DropDownListFor(Model => Model.Models, new SelectList(Enumerable.Empty<SelectListItem>(), "ModelId", "ModelName"),
"Select a Model", new { id = "ddlModels" })

</p>
<p>
@Html.DropDownListFor(Model => Model.Colours, new SelectList(Enumerable.Empty<SelectListItem>(), "ColourId", "ColourName"),
"Select a Colour", new { id = "ddlColours" })

</p>

And then, when we build and run we can get to choose the Car, Model and Make, a cascading dropdown built using jQuery and MVC 3.

You can download the scripts here.



European ASP.NET MVC 3 Hosting :: ASP.NET MVC 3 Render Partial View to String

clock August 5, 2011 07:48 by author Scott

You can see this post first ASP.NET MVC Render Partial View to String. This post shows how to implement a RenderPartialViewToString method. To avoid the need of a parent class for each controller that implements this (helper) method I decided to use the following extension methods:

/// <summary>
/// Controller extension class that adds controller methods
/// to render a partial view and return the result as string.
///
/// Based on http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial
view-to-string/

/// </summary>
public static class ControllerExtension
{ 

  /// <summary>
  /// Renders a (partial) view to string.
  /// </summary>
  /// <param name="controller">Controller to extend</param>
  /// <param name="viewName">(Partial) view to render</param>
  /// <returns>Rendered (partial) view as string</returns>
  public static string RenderPartialViewToString(this Controller controller, string viewName)
  {
    return controller.RenderPartialViewToString(viewName, null);
  } 

  /// <summary>
  /// Renders a (partial) view to string.
  /// </summary>
  /// <param name="controller">Controller to extend</param>
  /// <param name="viewName">(Partial) view to render</param>
  /// <param name="model">Model</param>
  /// <returns>Rendered (partial) view as string</returns>
  public static string RenderPartialViewToString(this Controller controller, string viewName, object model)
  {
    if (string.IsNullOrEmpty(viewName))
      viewName = controller.ControllerContext.RouteData.GetRequiredString("action"); 

      controller.ViewData.Model = model; 

      using (var sw = new StringWriter())
      {
        var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
        var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
        viewResult.View.Render(viewContext, sw); 

        return sw.GetStringBuilder().ToString();
      }
    } 

}

Using this extension methods my controller actions handling the AJAX requests look like this:

[HttpPost]
public ActionResult Update(int id, Model model)
{
  if (ModelState.IsValid)
  {
    // Update the database
    [...] 

    // Partial/FormUpdated contains a success message
    return Json(new Object[] { true, this.RenderPartialViewToString("Partial/FormUpdated", model) });
  } 

  // Partial/Form contains the form with all server-side validation errors
  return Json(new Object[] { false, this.RenderPartialViewToString("Partial/Form", model) });
}



European ASP.NET MVC 3 Hosting :: EditorTemplates in ASP.NET MVC 3

clock August 4, 2011 07:44 by author Scott

In this tutorial, I will show you how to use EditorTemplates in ASP.NET MVC 3.

1. Create the template

In this article, we create the file called “Address.cshtml”. And we place it into “Shared/EditorTemplate/” folder. You can preview it on the image below



2. Create model and controller

Model
: Person Class

public class Person
{
    public Person()
    {
        Name = "George";

        var newYork = new Address
                  {
                      City = "NY",
                      Country = "USA",
                      PostalCode = "10021",
                      Street = "34 Vosges street"
                  };

        var paris = new Address
                        {
                            City = "Paris",
                            Country = "France",
                            PostalCode = "75001",
                            Street = "13 Leclerc street"
                        };

        var bruxelles = new Address
                            {
                                City = "Bruxelles",
                                Country = "Belgium",
                                PostalCode = "65478",
                                Street = "01 Garden Street"
                            };

        Addresses = new List<Address> { newYork, paris, bruxelles };
    }

    public string Name { get; set; }
    public List<Address> Addresses { get; set; }
}

Model : Address Class

public class Address
{
    public string Street { get; set; }
    public string PostalCode { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}


Controler : PersonWithAddress

public class PersonWithAddressController : Controller

{
    public ActionResult Index()
    {
        return View(new Person());
    }
}

3. The View

Here, we strongly typed our View with our model (Person). (Of course it’s not mandatory to use strongly typed view if you want to use EditorTemplate). We want to be able to display the Person with all its addresses.


We call the Html helper EditorFor. For each Address object in the list, Razor will call the Address template.

@model MvcEditorTemplates.Models.Person
@{
    ViewBag.Title = "Person with Addresses";
}
<h2>Person</h2>
<p>
    @Html.LabelFor(model => model.Name)
    @Html.EditorFor(model => model.Name)
</p>   

<h2>Person Addresses</h2>
@Html.EditorFor(model => model.Addresses)

This is the preview



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