Home > front end >  ASP.NET Core model binding values are null
ASP.NET Core model binding values are null

Time:10-11

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 >
        <div  data-wow-duration="1s" data-wow-delay="0.7s">
            <div >
                <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 >
                <span ><i ></i> @Html.DisplayFor(modelItem => item.PostedDateTime)</span>
                @*<span ><a href="#"><i ></i> 4 Comments</a></span>*@
            </div><!--post info-->

            <div >
                <h4><a  href="blog_single_post.html">@Html.DisplayFor(modelItem => item.BlogTitle)</a></h4>
                <p >@Html.DisplayFor(modelItem => item.BlogContent)</p>
                <a  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 ' 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

CodePudding user response:

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  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

  • Related