0

I need to generate urls for use in javascript. I don't think my current solution is very readable.

//Navigation during load: Id from MVC or hash or zero.
var m_departmentId = <%= ViewContext.RouteData.Values["id"] ?? 0 %>;
if(0 == m_departmentId)
{            
    var hash = location.hash;            
    //Only one hash value
    var id = parseInt(hash.substring(2));

    //If it's a real Id, use it.
    if (!isNaN(id)) {
        m_departmentId = id;

    }
}

var gridUrl = '<%= Url.Action("GetEmployees", "Company", new { area = "" }) %>/' + m_departmentId;

This script is placed at top of my page javascript where I translate aspnet-variables to js-variables.

Can I get rid of the first javascript?
Can I improve the readability of the last row? Imho it's rather hideous, especially within my page javascript.
Other improvements?


Improvement 1:

var gridUrl = '<%= Url.Content("~/Company/GetEmployees/") }) %>' + m_departmentId;

T4MVC didn't work when the action was the default action for the route, because the action was stripped from the path when no action argument was used.

1
  • @Darin Dimitrov It's used for the ajax navigation (with deep linking) on that page (explorer like interface with tree and grid). Commented Sep 21, 2011 at 21:44

1 Answer 1

2

I think you need the JavaScript for the hash. You can't read hashes server-side.

T4MVC may help you with the "ugly" URL generation. It will at least get rid of the magic strings (still can't believe they went that route with the UrlHelper).

Sign up to request clarification or add additional context in comments.

3 Comments

This works: var gridUrl = '<%= Url.Action(MVC.Company.GetEmployees()) %>/' + m_departmentId; It's not much better, but it's at least in a sensible order.
I also tend to use format strings in these situations. I think it adds to the readability, although it's probably overkill here. String.Format("{0}/{1}", Url.Action(MVC.Company.GetEmployees()), m_departmentId);
Ran into a problem with actions named index when I later need to add the id after. The t4mvc-generated url removes /index which later would result in /Controller/Id instead of /Controller/Action/Id. I had to write it like this var m_personUrlTemplate = '<%= Url.Content("~/Person/Index/") %>';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.