Archive for ‘ASP.NET’

September 25, 2012

ASP.NET MVC with Ajax calls to controller actions

Recently I was trouble shooting an ASP.NET MVC project which relies on some Ajax calls to controller
actions. The project has a view in which there are a couple of drop down lists which trigger an
action result as soon as an item is selected in each list.

The view has a drop down list defined as follows:

@Html.DropDownList("searchTemplate",
new SelectList(Model.DefaultSearchTemplates, "SearchFilterTemplateId", "Name"), "Choose")

And a change event triggers the action result:

$("select#searchTemplate").change(function () {
    var selectedTemplate = $("select#searchTemplate").val();
    
    if (selectedTemplate) {
	$.ajax({
	    url: '@Url.Action("ApplySearchTemplate","Quote")',
	    data: { templateId: selectedTemplate }
	});
    }
});

The functionality of the Action isn’t important for this post, but it essentially saves a users
last search criteria so that the next time they log in, they will see the same results.

The problem with the application was that the selection of a search template only worked once. And
on further inspection, it turned out that the controller action was not being called at all after
the first time.

This was an interesting problem because the change event was certainly being called every time that
an item was selected in the list. My initial thought was that there must be some bug in ajax itself,
but it did seem fairly unlikely that such a bug would have gone un-noticed.

As expected, after digging through the ajax source, the problem became apparant; user error. Ajax
caches requests by default and even though these particular calls are not returning values nor
expecting results; the requests are still cached.

Since the requests were cached, each subsequent selection in the dropdown list resulted in ajax
“ignoring” the request since it “already knew the results”.

Once I understood what was happening, it was just a matter of disabling ajax caching for the view.
There are two ways to disable the cache; the first is to disable it individually for each request:

$("select#searchTemplate").change(function () {
    var selectedTemplate = $("select#searchTemplate").val();
    
    if (selectedTemplate) {
	$.ajax({
	    url: '@Url.Action("ApplySearchTemplate","Quote")',
	    data: { templateId: selectedTemplate },
	    cache: false
	});
    }
});

The second option is to globally disable ajax caching using ajaxSetup:

$.ajaxSetup({ cache: false });

Since this particular view has multiple similar calls to controller actions, setting it globally was
the solution that was chosen.

August 27, 2012

ASP.NET MVC3 with Razor view engine using Monodevelop and Ubuntu 12.04

Developing .Net web applications in a linux environment has been somewhat of a personal curiosity for quite some time. I have Ubuntu 12.04 installed in a dual boot configuration and every once in a while get an urge to actually boot Ubuntu and tinker with Monodevelop to see how far along the project has come. Since most of my time is spent developing ASP.NET MVC3 applications, I decided to see if it was possible to get a simple application running using the Razor view engine.

The last time I attempted this (over a year ago), it turned out to be more of a pain getting a web server configured to run ASP.NET applications than it was worth. The experience this time was much better as Monodevelop has xsp4 integrated out of the box for serving the web pages. xsp4 is a minimalistic web server which hosts the ASP.NET runtime.

To be honest, I was hoping that by now Monodevelop would have support for the Razor view engine and it would just work ‘out of the box’. This of course was just wishful thinking. However, the actual process to get it working isn’t a deal breaker anymore; especially after you have done it once.

To begin with, you will want to get the latest version of Monodevelop. The Ubuntu repository is a bit behind, so using a ppa is your best bet:

sudo add-apt-repository ppa:keks9n/monodevelop-latest
sudo apt-get update
sudo apt-get install monodevelop

This process will take a few minutes depending on your connection speed. Once installed, launch Monodevelop and click Start New Solution. Select ASP.NET MVC Project from the C# section and give your project a name and location.

Once the project is created, compile it and optionally run it. Compiling the project will create a bin folder with the relevant assemblies. If your project will not compile and the message refers to a .NET 3.5 compiler not being found, be sure to change your build to use .NET 4.0. Right click on your project (not the solution) and select options. Under build, click on ‘General’ and select ‘Mono/.NET 4.0′.

In the bin folder, there will be a System.Web.Mvc.dll. This is an ‘old’ version and will be replaced. The first thing to do at this point is remove that reference from your project. In the solution explorer of Monodevelop, expand the references and then right-click delete System.Web.Mvc.

The next steps require that you have some assemblies from a Windows compiled MVC 3 project. If you don’t have access to a Windows machine, just google for them. The assemblies that you will want to copy over to the bin folder are as follows:

  • System.Web.Helpers.dll
  • System.Web.Mvc.dll
  • System.Web.Razor.dll
  • System.Web.WebPages.dll
  • System.Web.WebPages.Deployment.dll
  • System.Web.WebPages.Razor.dll
  • Once you have copied them to the bin folder, add them as references to your project. To do this, right click ‘references’ in the solution explorer and select ‘edit references’. Click the .Net Assembly tab and double click the bin folder. Control-click all of the above dll’s and then click the ‘add’ button.

    Almost there. The project that was created by Monodevelop is using aspx pages. You will need to configure the project to use the Razor view engine. You can manually edit the Web.config to include razor, or be lazy like I was and just copy everything from a project created in Visual Studio. Here’s a complete Web.Config that you can copy and paste:

    <?xml version="1.0"?>
    
    <configuration>
      <configSections>
        <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
          <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
          <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
        </sectionGroup>
      </configSections>
    
      <system.web.webPages.razor>
        <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <pages pageBaseType="System.Web.Mvc.WebViewPage">
          <namespaces>
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Routing" />
          </namespaces>
        </pages>
      </system.web.webPages.razor>
    
      <appSettings>
        <add key="webpages:Enabled" value="false" />
      </appSettings>
    
      <system.web>
        <httpHandlers>
          <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
        </httpHandlers>
    
        <!--
            Enabling request validation in view pages would cause validation to occur
            after the input has already been processed by the controller. By default
            MVC performs request validation before a controller processes the input.
            To change this behavior apply the ValidateInputAttribute to a
            controller or action.
        -->
        <pages
            validateRequest="false"
            pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
            pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
            userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
          <controls>
            <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
          </controls>
        </pages>
      </system.web>
    
      <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
    
        <handlers>
          <remove name="BlockViewHandler"/>
          <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
        </handlers>
      </system.webServer>
    </configuration>
    

    It’s probably a good idea to copy Global.asax.cs for updated route configuration. This is the step where you will be glad to have copied System.Web.Mvc from a Windows build. Without it, you will not be able to compile the project because GlobalFilterCollection will not exist. Replace the complete class with the following:

        public class MvcApplication : System.Web.HttpApplication
        {
            public static void RegisterGlobalFilters(GlobalFilterCollection filters)
            {
                filters.Add(new HandleErrorAttribute());
            }
    
            public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
                routes.MapRoute(
                    "Default", // Route name
                    "{controller}/{action}/{id}", // URL with parameters
                    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
                );
    
            }
    
            protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
    
                RegisterGlobalFilters(GlobalFilters.Filters);
                RegisterRoutes(RouteTable.Routes);
            }
        }
    

    Finally, rename ~/Views/Home/Index.aspx to Index.cshtml and then replace its contents with the following:

    @{
        ViewBag.Title = "Home Page";
    }
    
    <h2>@ViewBag.Message</h2>
    <p>
        To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>
    </p>
    

    If all went well, you can compile and run your project by hitting F5.

    July 2, 2012

    List recent WordPress Blog Posts in ASP.NET MVC

    Recently I was tasked with adding a list of recent blog posts from our WordPress site inside of an ASP.NET MVC web site. The initial strategy was going to involve fetching from the RSS feed, but after discovering the WordPress supported XML-RPC, I decided to explore that route first.

    Using XML-RPC was supposed to be easy considering there is an available .NET library for it created by Charles Cook. The task should have been further simplified because there are several C# WordPress wrappers available.

    After spending time with a couple of the WordPress wrappers available, it quickly became clear that the process of updating the wrappers to comply with the latest version of WordPress would be far more work than it was worth; especially considering the scope of this task.

    So it was back to the original strategy of creating an RSS reader specifically for WordPress. After digging around a bit, I thankfully stumbled across the Syndication Feed class that is available in .Net 4.0 and above.

    The Syndication Feed class basically provides the quick and easy solution that I was looking for while exploring the XML-RPC route. It really turned out to be a lot easier than I thought it could ever be.

    So let’s get started. For this, I will assume that you are using an existing MVC application.

    The first step is to add a reference to System.ServiceModel to your project as this is where the Syndication Feed class resides.

    The second step is to create a View Model that will define a List of SyndicationItem’s:

    using System.Collections.Generic;
    using System.ServiceModel.Syndication;
    
    namespace MvcApplication1.Models
    {
        public class FeedViewModel
        {
            public FeedViewModel()
            {
                Posts = new List<SyndicationItem>();
            }
    
            public List<SyndicationItem> Posts { get; set; } 
        }
    }
    

    And in the Controller, we will need to populate the list:

    using System.Linq;
    using System.Web.Mvc;
    using System.ServiceModel.Syndication;
    using System.Xml;
    using MvcApplication1.Models;
    
    namespace MvcApplication1.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                var model = new FeedViewModel();
    
                using (var reader = XmlReader.Create("http://blog.yojimbocorp.com/feed/"))
                {
                    var feed = SyndicationFeed.Load(reader);
                    foreach (var post in feed.Items.Take(10))
                    {
                        model.Posts.Add(post);
                    }
                }
    
                return View(model);
            }
        }
    }
    

    You will of course want to customize the reader URL to be your own and most likely will want to create a configuration entry for it.

    And finally, display the data in your view:

    @model MvcApplication1.Models.FeedViewModel
               
    @foreach (var post in Model.Posts)
    {
        <td><a href="@post.Id" target="_blank">@Html.DisplayFor(model => post.Title.Text)</a></td>
        <br />
        
    }
    

    I highly recommend reviewing the SyndicationItem documentation when creating your view.

    March 20, 2012

    Securing static content with ASP.NET forms authentication

    A colleague of mine recently asked me how to secure static content on an IIS server and I thought I would quickly list the steps here for others that are looking for a quick guide on how to do it.

    First, the URL Authorization role service should be enabled on the IIS server. To do this, open the Server Manager and go to Roles -> Web Server (IIS) -> Add Role Services and then click the checkbox for URL Authorization.

    Next, the Manage pipeline mode should be set to Integrated for the Application Pool that the application is running under. You can verify this by opening the IIS Manager and going to the Connections pane. Expand ‘Sites’ and navigate to your web site (or application). In the Actions pane, click Advanced Settings. Then click on the General Section followed by clicking the Application Pool entry.

    Lastly, the web.config will need to instruct IIS to use ASP.NET’s UrlAuthorization Module and / or FormsAuthentication module. Here’s an example for both:

      <system.webServer>
        <modules>
    . . . removed other modules …
          <remove name="FormsAuthenticationModule" />
          <add name="FormsAuthenticationModule" type="System.Web.Security.FormsAuthenticationModule" />
    
          <remove name="UrlAuthorization" />
          <add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule" />
    
        </modules>

    Forms authentication requires that you specify <authorization> tags. Here’s an example that allows ‘anonymous’ to download images:

    <configuration>
      <system.web>
        <authorization>

    <deny users=”?” />

    </authorization>

    . . . removed other config . .

      </system.web>
    
      <location path="ErrorPages">
        <system.web>
          <authorization>
            <allow users="*" />
          </authorization>
        </system.web>
      </location>
    
      <location path="Images">
        <system.web>
          <authorization>
            <allow users="*" />
          </authorization>
        </system.web>
      </location>

    This should be all that is required for securing your static content with ASP.NET forms authentication. For further reading, I would suggest this page.

    Follow

    Get every new post delivered to your Inbox.