Getting problem to generate Absolute url in MVC

Hi I have created an mvc website which works fine from localhost if I code something like this:

    <base href="http://localhost:5400/" />
    <li><a class="home" href="/Home/Index/">Home</a></li>
    <li class="wish"><a class="wishlist" href="/Products/Index/" id="wishlist-total">Products</a></li>
     <li><a class="account" href="/Home/Contact/">Contact Us</a></li>

      

But now, to start it live, if I try to change this:

  <base href="http://localhost:5400/" />   

      

with this:

 <base href="HttpContext.Current.Request.Url" />

      

then it actually gets the full root url everytime.So whenever I click on any menu and go to the next menu, it also restores the previous menu path.

For this problem, I tried using code which also doesn't work.

<li><a href="@Url.Action("Index", "Home", null, Request.Url.Scheme)">Home</a></li>
<li><a href="@Url.Action("Index","Products",null,Request.Url.Scheme)">Products</a></li>
<li>  <a href="@Url.Action("Contact","Home",null,Request.Url.Scheme)">Contact</a></li>

      

In my opinion this code will work, but if I try to pass "null" as the third parameter then I give an error:

ERROR: "null" is not declared. The constant "Zero" is no longer supported; use "System.DBNull" instead.

Can someone please suggest what I need to change?

thank

+3


source to share


1 answer


Quick fix ...

@Url.Action("Index", "Home")

      

There is no need to enter null

as a parameter ... if you want to indicate that the parameter can be null, then you need to determine that it is in the route itself, and if the parameter is missing, then it will know that the value is implicitly null ...



// http://yoursite/Example/{id}
[Route("~/Example/{id}"] // Can't be null
public ActionResult Example(string id){ return View(); }

// http://yoursite/ExampleTwo/
[Route("~/ExampleTwo/{id?} // Can be null
public ActionResult ExampleTwo(string id) { return View(); }

      

TL; DR if you want more bugs ...

  • Your problem actually points to a much bigger problem ... it looks like you are accepting a request from a URI directly into a SQL query ... if you do, you open yourself up to injection attacks and as much as part of me feels that anyone who does this pretty much comes to them ... I can't stand and just speak ... sanitize any data you get from the user, no matter where they come from, example

  • Remove all those magic lines ... you shouldn't have any lines like the one you just displayed ...

    // Bad...
    <a class="home" href="/Home/Index/">  
    
    // Better...
    <a class="home" href="@Url.Action("Index", "Home")">Home</a>
    
    // Good
    @Html.ActionLink("Home", "Index", "Home")
    
          

0


source







All Articles