ASP.Net MVC always routes 0 to the method












0















Here is my view (full view)



@model List<BlogPostLayoutModel>
@{
ViewData["Title"] = "Index";
}

@foreach (var item in Model)
{
<div class="row">
<div class="col-md-12">
<h2 class="text-center">
@item.Title
</h2>
<div class="col-md-9 thumbnail">
<img src="/home/getimage/@item.IDPost" />
</div>
<p>@item.Content</p>
</div>
</div>
}


And here is Home controllers GetImage method



public async Task<ActionResult> GetImage(int id)
{
var post = await _blogContext.Posts.FirstOrDefaultAsync(m => m.IDPost == id);

return File(post.Image, post.Image_Extension);
}


When i debug, i can see that each object in Model has an id of ~1000 (some real number in database) but when i debug the GetImage method, it always get passed 0.



Routing definition:



app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{pageNumber=1}");
});


Controller method:



public async Task<IActionResult> Index(int pageNumber)
{
blogPages = BlogPages();
ViewBag.pageNumber = pageNumber;
ViewBag.blogPages = blogPages;
List<BlogPostLayoutModel> bPLMList = PostsForBlogPage(pageNumber);
return View(bPLMList);
}


And BlogPostLayourModel definition (without the unnecessary methods):



public class BlogPostLayoutModel
{
public int IDPost { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public string AuthorUserName { get; set; }
public DateTime DateCreated { get; set; }
public byte ImageFromPost { get; set; }
public string Image_Extension { get; set; }
}









share|improve this question

























  • @Stefan Yeah, but then if i had 10 methods with their own ids, i would need to change them all to pageNumber, right?

    – Tomato
    Nov 27 '18 at 16:49











  • Yes, therefore, see my answer for an explanation.

    – Stefan
    Nov 27 '18 at 16:52
















0















Here is my view (full view)



@model List<BlogPostLayoutModel>
@{
ViewData["Title"] = "Index";
}

@foreach (var item in Model)
{
<div class="row">
<div class="col-md-12">
<h2 class="text-center">
@item.Title
</h2>
<div class="col-md-9 thumbnail">
<img src="/home/getimage/@item.IDPost" />
</div>
<p>@item.Content</p>
</div>
</div>
}


And here is Home controllers GetImage method



public async Task<ActionResult> GetImage(int id)
{
var post = await _blogContext.Posts.FirstOrDefaultAsync(m => m.IDPost == id);

return File(post.Image, post.Image_Extension);
}


When i debug, i can see that each object in Model has an id of ~1000 (some real number in database) but when i debug the GetImage method, it always get passed 0.



Routing definition:



app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{pageNumber=1}");
});


Controller method:



public async Task<IActionResult> Index(int pageNumber)
{
blogPages = BlogPages();
ViewBag.pageNumber = pageNumber;
ViewBag.blogPages = blogPages;
List<BlogPostLayoutModel> bPLMList = PostsForBlogPage(pageNumber);
return View(bPLMList);
}


And BlogPostLayourModel definition (without the unnecessary methods):



public class BlogPostLayoutModel
{
public int IDPost { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public string AuthorUserName { get; set; }
public DateTime DateCreated { get; set; }
public byte ImageFromPost { get; set; }
public string Image_Extension { get; set; }
}









share|improve this question

























  • @Stefan Yeah, but then if i had 10 methods with their own ids, i would need to change them all to pageNumber, right?

    – Tomato
    Nov 27 '18 at 16:49











  • Yes, therefore, see my answer for an explanation.

    – Stefan
    Nov 27 '18 at 16:52














0












0








0








Here is my view (full view)



@model List<BlogPostLayoutModel>
@{
ViewData["Title"] = "Index";
}

@foreach (var item in Model)
{
<div class="row">
<div class="col-md-12">
<h2 class="text-center">
@item.Title
</h2>
<div class="col-md-9 thumbnail">
<img src="/home/getimage/@item.IDPost" />
</div>
<p>@item.Content</p>
</div>
</div>
}


And here is Home controllers GetImage method



public async Task<ActionResult> GetImage(int id)
{
var post = await _blogContext.Posts.FirstOrDefaultAsync(m => m.IDPost == id);

return File(post.Image, post.Image_Extension);
}


When i debug, i can see that each object in Model has an id of ~1000 (some real number in database) but when i debug the GetImage method, it always get passed 0.



Routing definition:



app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{pageNumber=1}");
});


Controller method:



public async Task<IActionResult> Index(int pageNumber)
{
blogPages = BlogPages();
ViewBag.pageNumber = pageNumber;
ViewBag.blogPages = blogPages;
List<BlogPostLayoutModel> bPLMList = PostsForBlogPage(pageNumber);
return View(bPLMList);
}


And BlogPostLayourModel definition (without the unnecessary methods):



public class BlogPostLayoutModel
{
public int IDPost { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public string AuthorUserName { get; set; }
public DateTime DateCreated { get; set; }
public byte ImageFromPost { get; set; }
public string Image_Extension { get; set; }
}









share|improve this question
















Here is my view (full view)



@model List<BlogPostLayoutModel>
@{
ViewData["Title"] = "Index";
}

@foreach (var item in Model)
{
<div class="row">
<div class="col-md-12">
<h2 class="text-center">
@item.Title
</h2>
<div class="col-md-9 thumbnail">
<img src="/home/getimage/@item.IDPost" />
</div>
<p>@item.Content</p>
</div>
</div>
}


And here is Home controllers GetImage method



public async Task<ActionResult> GetImage(int id)
{
var post = await _blogContext.Posts.FirstOrDefaultAsync(m => m.IDPost == id);

return File(post.Image, post.Image_Extension);
}


When i debug, i can see that each object in Model has an id of ~1000 (some real number in database) but when i debug the GetImage method, it always get passed 0.



Routing definition:



app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{pageNumber=1}");
});


Controller method:



public async Task<IActionResult> Index(int pageNumber)
{
blogPages = BlogPages();
ViewBag.pageNumber = pageNumber;
ViewBag.blogPages = blogPages;
List<BlogPostLayoutModel> bPLMList = PostsForBlogPage(pageNumber);
return View(bPLMList);
}


And BlogPostLayourModel definition (without the unnecessary methods):



public class BlogPostLayoutModel
{
public int IDPost { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public string AuthorUserName { get; set; }
public DateTime DateCreated { get; set; }
public byte ImageFromPost { get; set; }
public string Image_Extension { get; set; }
}






c# asp.net-core-mvc






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 28 '18 at 0:55









Tetsuya Yamamoto

16.6k42241




16.6k42241










asked Nov 27 '18 at 16:28









TomatoTomato

507




507













  • @Stefan Yeah, but then if i had 10 methods with their own ids, i would need to change them all to pageNumber, right?

    – Tomato
    Nov 27 '18 at 16:49











  • Yes, therefore, see my answer for an explanation.

    – Stefan
    Nov 27 '18 at 16:52



















  • @Stefan Yeah, but then if i had 10 methods with their own ids, i would need to change them all to pageNumber, right?

    – Tomato
    Nov 27 '18 at 16:49











  • Yes, therefore, see my answer for an explanation.

    – Stefan
    Nov 27 '18 at 16:52

















@Stefan Yeah, but then if i had 10 methods with their own ids, i would need to change them all to pageNumber, right?

– Tomato
Nov 27 '18 at 16:49





@Stefan Yeah, but then if i had 10 methods with their own ids, i would need to change them all to pageNumber, right?

– Tomato
Nov 27 '18 at 16:49













Yes, therefore, see my answer for an explanation.

– Stefan
Nov 27 '18 at 16:52





Yes, therefore, see my answer for an explanation.

– Stefan
Nov 27 '18 at 16:52












2 Answers
2






active

oldest

votes


















2














So your route says that the third route parameter is called pageNumber. Now consider your image link:



<img src="/home/getimage/@item.IDPost" />


Post ID is going to be mapped to pageNumber when this request is being routed. Now take a look at the action declaration:



public async Task<ActionResult> GetImage(int id)


This says that the action expects a request to have a parameter called id. After the request is routed to this action, model binding happens, and during this process route and request parameters are being mapped to action's input. In this case there model binder is not going to find the id the action needs, because there is nothing in request with that name. The only parameter in there has a name pageNumber. Thus it initializes id with a default value, 0.



One way to fix this would be to use query string instead of route parameter, and this way explicitly name post ID as, well, id:



<img src="/home/getimage?id=@item.IDPost" />





share|improve this answer































    2














    Actually, using pageNumber as default parameter, is under normal circumstances, not really a wise choice.



    You should alter your routing to:



    app.UseMvc(routes =>
    {
    routes.MapRoute(
    name: "default",
    template: "{controller=Home}/{action=Index}/{id?}");
    });


    This will break the code which uses pageNumber as default route, but you'll gain the fact that this will work:



    <img src="/home/getimage/@item.IDPost" />


    For other links, using pageNumber, you'll need the following syntax:



    <img src="/home/getimage?pageNumber=@item.PageNumber" />




    The motivation for this all, is due to the fact that:




    • quite often, you'll need a (detail)record and is often queried by id

    • pageNumber often comes with pageSize, so is basically often a more complex object.




    Additionally, if you want to make the pageNumber a default parameter for a single action, you can mark it with the route attribute:



    [Route("{pageNumber}")]
    public async Task<IActionResult> Index(int pageNumber)


    More information on routing can be found here and here (assuming you are using asp.net Core.






    share|improve this answer


























    • Problem for me was, that i need the default route to be the blogs first page, and that was my solution for the problem. Is there any way i can achieve that, so that i still route default(ly) to first page (Home/Index/1) and can use <img src="/home/getimage/@item.IDPost" /> markup? (sorry for being off topic from the OP)

      – Tomato
      Nov 27 '18 at 16:52











    • Yes, there are some way's to do that, I added a solution for that.

      – Stefan
      Nov 27 '18 at 16:58











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53504059%2fasp-net-mvc-always-routes-0-to-the-method%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    So your route says that the third route parameter is called pageNumber. Now consider your image link:



    <img src="/home/getimage/@item.IDPost" />


    Post ID is going to be mapped to pageNumber when this request is being routed. Now take a look at the action declaration:



    public async Task<ActionResult> GetImage(int id)


    This says that the action expects a request to have a parameter called id. After the request is routed to this action, model binding happens, and during this process route and request parameters are being mapped to action's input. In this case there model binder is not going to find the id the action needs, because there is nothing in request with that name. The only parameter in there has a name pageNumber. Thus it initializes id with a default value, 0.



    One way to fix this would be to use query string instead of route parameter, and this way explicitly name post ID as, well, id:



    <img src="/home/getimage?id=@item.IDPost" />





    share|improve this answer




























      2














      So your route says that the third route parameter is called pageNumber. Now consider your image link:



      <img src="/home/getimage/@item.IDPost" />


      Post ID is going to be mapped to pageNumber when this request is being routed. Now take a look at the action declaration:



      public async Task<ActionResult> GetImage(int id)


      This says that the action expects a request to have a parameter called id. After the request is routed to this action, model binding happens, and during this process route and request parameters are being mapped to action's input. In this case there model binder is not going to find the id the action needs, because there is nothing in request with that name. The only parameter in there has a name pageNumber. Thus it initializes id with a default value, 0.



      One way to fix this would be to use query string instead of route parameter, and this way explicitly name post ID as, well, id:



      <img src="/home/getimage?id=@item.IDPost" />





      share|improve this answer


























        2












        2








        2







        So your route says that the third route parameter is called pageNumber. Now consider your image link:



        <img src="/home/getimage/@item.IDPost" />


        Post ID is going to be mapped to pageNumber when this request is being routed. Now take a look at the action declaration:



        public async Task<ActionResult> GetImage(int id)


        This says that the action expects a request to have a parameter called id. After the request is routed to this action, model binding happens, and during this process route and request parameters are being mapped to action's input. In this case there model binder is not going to find the id the action needs, because there is nothing in request with that name. The only parameter in there has a name pageNumber. Thus it initializes id with a default value, 0.



        One way to fix this would be to use query string instead of route parameter, and this way explicitly name post ID as, well, id:



        <img src="/home/getimage?id=@item.IDPost" />





        share|improve this answer













        So your route says that the third route parameter is called pageNumber. Now consider your image link:



        <img src="/home/getimage/@item.IDPost" />


        Post ID is going to be mapped to pageNumber when this request is being routed. Now take a look at the action declaration:



        public async Task<ActionResult> GetImage(int id)


        This says that the action expects a request to have a parameter called id. After the request is routed to this action, model binding happens, and during this process route and request parameters are being mapped to action's input. In this case there model binder is not going to find the id the action needs, because there is nothing in request with that name. The only parameter in there has a name pageNumber. Thus it initializes id with a default value, 0.



        One way to fix this would be to use query string instead of route parameter, and this way explicitly name post ID as, well, id:



        <img src="/home/getimage?id=@item.IDPost" />






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 27 '18 at 16:47









        AndreiAndrei

        47.9k77092




        47.9k77092

























            2














            Actually, using pageNumber as default parameter, is under normal circumstances, not really a wise choice.



            You should alter your routing to:



            app.UseMvc(routes =>
            {
            routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
            });


            This will break the code which uses pageNumber as default route, but you'll gain the fact that this will work:



            <img src="/home/getimage/@item.IDPost" />


            For other links, using pageNumber, you'll need the following syntax:



            <img src="/home/getimage?pageNumber=@item.PageNumber" />




            The motivation for this all, is due to the fact that:




            • quite often, you'll need a (detail)record and is often queried by id

            • pageNumber often comes with pageSize, so is basically often a more complex object.




            Additionally, if you want to make the pageNumber a default parameter for a single action, you can mark it with the route attribute:



            [Route("{pageNumber}")]
            public async Task<IActionResult> Index(int pageNumber)


            More information on routing can be found here and here (assuming you are using asp.net Core.






            share|improve this answer


























            • Problem for me was, that i need the default route to be the blogs first page, and that was my solution for the problem. Is there any way i can achieve that, so that i still route default(ly) to first page (Home/Index/1) and can use <img src="/home/getimage/@item.IDPost" /> markup? (sorry for being off topic from the OP)

              – Tomato
              Nov 27 '18 at 16:52











            • Yes, there are some way's to do that, I added a solution for that.

              – Stefan
              Nov 27 '18 at 16:58
















            2














            Actually, using pageNumber as default parameter, is under normal circumstances, not really a wise choice.



            You should alter your routing to:



            app.UseMvc(routes =>
            {
            routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
            });


            This will break the code which uses pageNumber as default route, but you'll gain the fact that this will work:



            <img src="/home/getimage/@item.IDPost" />


            For other links, using pageNumber, you'll need the following syntax:



            <img src="/home/getimage?pageNumber=@item.PageNumber" />




            The motivation for this all, is due to the fact that:




            • quite often, you'll need a (detail)record and is often queried by id

            • pageNumber often comes with pageSize, so is basically often a more complex object.




            Additionally, if you want to make the pageNumber a default parameter for a single action, you can mark it with the route attribute:



            [Route("{pageNumber}")]
            public async Task<IActionResult> Index(int pageNumber)


            More information on routing can be found here and here (assuming you are using asp.net Core.






            share|improve this answer


























            • Problem for me was, that i need the default route to be the blogs first page, and that was my solution for the problem. Is there any way i can achieve that, so that i still route default(ly) to first page (Home/Index/1) and can use <img src="/home/getimage/@item.IDPost" /> markup? (sorry for being off topic from the OP)

              – Tomato
              Nov 27 '18 at 16:52











            • Yes, there are some way's to do that, I added a solution for that.

              – Stefan
              Nov 27 '18 at 16:58














            2












            2








            2







            Actually, using pageNumber as default parameter, is under normal circumstances, not really a wise choice.



            You should alter your routing to:



            app.UseMvc(routes =>
            {
            routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
            });


            This will break the code which uses pageNumber as default route, but you'll gain the fact that this will work:



            <img src="/home/getimage/@item.IDPost" />


            For other links, using pageNumber, you'll need the following syntax:



            <img src="/home/getimage?pageNumber=@item.PageNumber" />




            The motivation for this all, is due to the fact that:




            • quite often, you'll need a (detail)record and is often queried by id

            • pageNumber often comes with pageSize, so is basically often a more complex object.




            Additionally, if you want to make the pageNumber a default parameter for a single action, you can mark it with the route attribute:



            [Route("{pageNumber}")]
            public async Task<IActionResult> Index(int pageNumber)


            More information on routing can be found here and here (assuming you are using asp.net Core.






            share|improve this answer















            Actually, using pageNumber as default parameter, is under normal circumstances, not really a wise choice.



            You should alter your routing to:



            app.UseMvc(routes =>
            {
            routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
            });


            This will break the code which uses pageNumber as default route, but you'll gain the fact that this will work:



            <img src="/home/getimage/@item.IDPost" />


            For other links, using pageNumber, you'll need the following syntax:



            <img src="/home/getimage?pageNumber=@item.PageNumber" />




            The motivation for this all, is due to the fact that:




            • quite often, you'll need a (detail)record and is often queried by id

            • pageNumber often comes with pageSize, so is basically often a more complex object.




            Additionally, if you want to make the pageNumber a default parameter for a single action, you can mark it with the route attribute:



            [Route("{pageNumber}")]
            public async Task<IActionResult> Index(int pageNumber)


            More information on routing can be found here and here (assuming you are using asp.net Core.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 27 '18 at 17:07

























            answered Nov 27 '18 at 16:49









            StefanStefan

            8,52873761




            8,52873761













            • Problem for me was, that i need the default route to be the blogs first page, and that was my solution for the problem. Is there any way i can achieve that, so that i still route default(ly) to first page (Home/Index/1) and can use <img src="/home/getimage/@item.IDPost" /> markup? (sorry for being off topic from the OP)

              – Tomato
              Nov 27 '18 at 16:52











            • Yes, there are some way's to do that, I added a solution for that.

              – Stefan
              Nov 27 '18 at 16:58



















            • Problem for me was, that i need the default route to be the blogs first page, and that was my solution for the problem. Is there any way i can achieve that, so that i still route default(ly) to first page (Home/Index/1) and can use <img src="/home/getimage/@item.IDPost" /> markup? (sorry for being off topic from the OP)

              – Tomato
              Nov 27 '18 at 16:52











            • Yes, there are some way's to do that, I added a solution for that.

              – Stefan
              Nov 27 '18 at 16:58

















            Problem for me was, that i need the default route to be the blogs first page, and that was my solution for the problem. Is there any way i can achieve that, so that i still route default(ly) to first page (Home/Index/1) and can use <img src="/home/getimage/@item.IDPost" /> markup? (sorry for being off topic from the OP)

            – Tomato
            Nov 27 '18 at 16:52





            Problem for me was, that i need the default route to be the blogs first page, and that was my solution for the problem. Is there any way i can achieve that, so that i still route default(ly) to first page (Home/Index/1) and can use <img src="/home/getimage/@item.IDPost" /> markup? (sorry for being off topic from the OP)

            – Tomato
            Nov 27 '18 at 16:52













            Yes, there are some way's to do that, I added a solution for that.

            – Stefan
            Nov 27 '18 at 16:58





            Yes, there are some way's to do that, I added a solution for that.

            – Stefan
            Nov 27 '18 at 16:58


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53504059%2fasp-net-mvc-always-routes-0-to-the-method%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Contact image not getting when fetch all contact list from iPhone by CNContact

            count number of partitions of a set with n elements into k subsets

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks