Search code examples
c#asp.net-coremodel-binding

ASP.NET Core model binding values are null


I have the following code where I am looping through a property in the model object as follows. The BlogDataItems is of type

public IPagedList<BlogData> BlogDataItems { get; set; }

from using X.PagedList library. I am able to see the Image, title, body etc the values I am binding.

@foreach (var item in Model.BlogDataItems)
{
    <!-- === Blog item 1 === -->
    <div class="col-md-4 col-sm-6 m-bottom-40">
        <div class="blog wow zoomIn" data-wow-duration="1s" data-wow-delay="0.7s">
            <div class="blog-media">
                <a href="blog_single_post.html">
                    @*<img src="~/img/blog/b1.jpg" alt="" asp-append-version="true">*@
                    <img id="ItemPreview" src="data:image;base64,@System.Convert.ToBase64String(item.ImageData)" alt="Image" height="200" width="220" />
                </a>
            </div><!--post media-->

            <div class="blog-post-info clearfix">
                <span class="time"><i class="fa fa-calendar"></i> @Html.DisplayFor(modelItem => item.PostedDateTime)</span>
                @*<span class="comments"><a href="#"><i class="fa fa-comments"></i> 4 Comments</a></span>*@
            </div><!--post info-->

            <div class="blog-post-body">
                <h4><a class="title" href="blog_single_post.html">@Html.DisplayFor(modelItem => item.BlogTitle)</a></h4>
                <p class="p-bottom-20">@Html.DisplayFor(modelItem => item.BlogContent)</p>
                <a class="read-more" asp-action="DetailedView" asp-controller="BlogData" asp-route-blogItem="@HttpContextAccessor.HttpContext.Request.Query["item"]">Read More >></a>
            </div><!--post body-->
        </div> <!-- /.blog -->
    </div> <!-- /.inner-col -->
}

Now please see the 'a class="read-more"' element, I am trying to bind the item using asp-route-blogItem="@item" to the controller action method and all the values inside are either null or default. Please help.

[HttpGet]
public IActionResult DetailedView(BlogData blogItem)
{
    if (blogItem != null)
    {
    }

    return View(blogItem);
}

When I debug the code, this is what I have

Values are null or default


Solution

  • For your requirement,I think you could try asp-all-route-data instead of asp-route-yourkey

    I tried as below :

    @{
        var id = HttpContextAccessor.HttpContext.Request.Query["id"];
        var routedata = new Dictionary<string, string>();
        routedata.Add("id", id);
        routedata.Add("BlogTitle", "title");
        routedata.Add("BlogContent", "content");
    
    }
    
    .........
    
    <a class="read-more" asp-action="Privacy" asp-controller="Home"  asp-all-route-data="@routedata">Read More >></a>
    

    The Result:

    enter image description here

    you could check this document about modelbinding,and document about taghelper