简体   繁体   中英

.NET MVC: How in <a @Url.Action()> to send an Object In an Object?

Good for all:)

I want to easily submit a model for data filtering.

For quick sorting, I wrote tags by which the data will be sorted...

When I click on the link, the address bar becomes like this -> "&FilterData=Project.Web.Models.FilterData"

localhost/User?PageNum=1&SortOrder=NameAsc&FilterData=Project.Web.Models.FilterData
<a href="@Url.Action("Index", "User", new FilterRequest(filter, sort, pagination))"> First Name </a>

Here is the code for understanding)

FilterRequest.cs

public class FilterRequest
{
     public int PageNumber { get; set; } = 1;

     public SortType SortOrder { get; set; } = SortType.None;

     public FilterData FilterData { get; set; }
}

FilterData.cs

public class FilterData
{
   public string FirstName { get; set; }

   public string MiddleName { get; set; }

   public string LastName { get; set; }
}

How can You see the FilterData field is an object. Its fields are not displayed?

And this is how I receive data into the controller)

UserController.cs

public class UserController : Controller
{
    public IActionResult Index(FilterRequest request)
    {

    }
}

Please help me figure it out.. Display data from nested object:)

When I click on the link, the address bar becomes like this -> "&FilterData=Project.Web.Models.FilterData"

How in to send an Object In an Object?

To achieve your requirement of passing complex data to controller action via <a> tag, and make model binding work well, you can try following code snippet.

@{
    ViewData["Title"] = "Home Page";
    var pagination = 1;
    var sort = SortType.NameAsc;
    var filter = new FilterData { FirstName = "fn", MiddleName = "mn", LastName = "ln" };

    var parms = new Dictionary<string, string>
    {
        { "PageNumber", pagination.ToString() },
        { "SortOrder", SortType.NameAsc.ToString() },
        { "FilterData.FirstName",filter.FirstName},
        { "FilterData.MiddleName",filter.MiddleName},
        { "FilterData.LastName",filter.LastName}
    };
}

    <a asp-controller="Home" asp-action="Index" asp-all-route-data="parms">First Name</a>

The QueryString may look like this:

?PageNumber=1&SortOrder=NameAsc&FilterData.FirstName=fn&FilterData.MiddleName=mn&FilterData.LastName=ln

Test Result

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM