Archive for August, 2015

MVC – Fixing those broken images

MVC is full of all sorts of wonderful pitfalls features.

While working on a site, if I loaded up the default site I was debugging (http://localhost:3316) with no controller or actions segments , and the images on the page appeared. When I went all fancy and used http://localhost:3316/Home, then the images broke, and there was much gnashing of teeth. And a little crying, but that was probably the hot sauce.

However, I found an excellent post on Peter Seale’s blog about using prepending a “~/” onto a link. And I found that life got better when I did that. So if I have this image URL:

Images/cat.png

That may not work because of the twists and turns that is MVC. If your images do break when navigating to a particular view from a different way, try the “~/” trick:

~/Images/cat.png

You may just leave happy. Maybe.

Leave a comment

404 error calling an MVC controller action

There are two reasons I have seen this so far, and I have included both. I have creatively labeled them “Reason #1” and “Reason #2”. I leave it to you what will happen if I find a third reason.

Reason #1

I was using Ajax to call an MVC action like so:

        $.ajax({
            type: 'GET',
            url: '@Url.Content("~/Home/Stuff")',
            success: function (data) {
                $('#results').replaceWith(data);
            }, error: function (xhr) {
                alert(xhr.statusText);
            }
        });

And my Stuff action in the Home controller:

private ActionResult Stuff() {
            return PartialView("~/Views/Home/Stuff.cshtml");
}

But, I was deeply saddened to see that I was getting a “404 Not Found” error when I tried to do this. And it was because I made a simple mistake and hadn’t made my Stuff action public. Making that change fixed the issue:

public ActionResult Stuff() {
             return PartialView("~/Views/Home/Stuff.cshtml"); 
}

Reason #2

The second reason was that the URL was pointing to the wrong location. Shocker, I know. But here is the code that was causing the 404:

    $.ajax({
        url: '/Account/GetUsers',
        method: "GET",
    });

It appears that this would be fine – calling my controller Account, and the action GetUsers. However, this is ignoring that jQuery doesn’t know the complete path. The right code is:

    $.ajax({
        url: '@Url.Content("~/Account/GetUsers")',
        method: "GET",
    });

 

,

1 Comment

MVC – Retrieving data using jQuery and Ajax

Retrieving text using MVC through jQuery and Ajax is fairly simple. What I wanted to happen was to have a link that loaded a DIV when the user clicked it. So the really simple HTML:

<a href="#" onclick="load()">Support</a>

The jQuery for this request wasn’t much, either. Just a simple GET request pointing to the controller and action:

    function load() {
        $.ajax({
            type: 'GET',
            url: '@Url.Content("~/Home/Test")',
            success: function (data) {
                $('#results').text(data);
            }, error: function (xhr) {
                alert(xhr.statusText);
            }
        });
    }

And the Home controller, Test action:

public string Test() {
       return "Testing";
}

I did run into a problem where I was getting “404 Not Found” errors when I attempted to access the action. This was happening because my action was declared as private, so the 404 message made perfect sense.

, , ,

Leave a comment

ASP.NET membership database not appearing in the App_Data folder

Reading over some MVC documentation at https://msdn.microsoft.com/en-us/library/ff398049(v=vs.100).aspx, I noticed several people complaining that they couldn’t see the database after building the application. I went to my App_Data folder and I saw the same behavior – no database. Even restarting Visual Studio didn’t reveal the database.

However, you should be able to view the database by right clicking on the App_Data folder and selecting “Open Folder in File Explorer”.

ASP.NET membership database

ASP.NET membership database

You can also click on the “Show All Files” icon, and should reveal it as well:

Show All Files

Show All Files

Leave a comment

Getting Latitude / Longitude from a SQL Server Geometry

Do you need to pull the latitude and longitude values in format you know and love into a VARCHAR, like “41.848, -82.690”? No problem:

SELECT CONVERT(VARCHAR(20),[Geometry].STY) + ‘,’ + CONVERT(VARCHAR(20),[Geometry].STX) FROM MyPlaces

Leave a comment

Selecting empty SQL geometry values

Selecting empty geometries is easy. All you need is SQL Server, some data with a column of the Geometry data type, and this query:

SELECT * FROM ScottsFavoriteBars WHERE [Geometry].STIsEmpty() > 0

Leave a comment

‘Invalid column name’ error in SQL update statement

I was getting this error in my SQL statement, which was dynamically created in some C# code:

Invalid column name “385f35a5-697a-4238-b502-c5a72199d9c2”

An example of the statement:

INSERT INTO Test (ID)
VALUES ("385f35a5-697a-4238-b502-c5a72199d9c2")

This error was because my SQL INSERT statement had used double quotes around the text to be inserted instead of single quotes. Modifying the statement fixed it:

INSERT INTO Test (ID)
VALUES ('385f35a5-697a-4238-b502-c5a72199d9c2')

Leave a comment

ASP.NET MVC – Attribute to analyze calling controller and action

I needed to create an ASP.NET MVC attribute to attach to my controllers and have them affect all actions. The attribute would apply like so:

[ScottAuthorize]
public class AdvisoriesController : BaseController {
    // Really important business logic
}

What the attribute needed to do was analyze the controller and action being referenced, look up in a database whether the user actually had access to those actions (a custom role management system), and then grant or deny access based on the results. Here is a bit of that attribute to show how I did that:

public class ScottAuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute {
    protected override bool AuthorizeCore(HttpContextBase httpContext) {
        string controller = httpContext.Request.RequestContext.RouteData.Values["controller"].ToString();
        string action = httpContext.Request.RequestContext.RouteData.Values["action"].ToString();
        // Really important authorization stuff
        return true; // Or false, of course.
    }
}

If you are so awed by this code that you want to pay me, I’ll give you an address and you can send cash. I only accept pennies from 1970 – 1980 in good condition.

Leave a comment