简体   繁体   中英

Efficiently passing large number of parameters to ASP.NET MVC Controller Action

I'm trying to determine a more efficient way to pass a large number of parameters to my controller action. I tried to look at similar questions, but they didn't seem to offer any real explanation past what I have already implemented.

As an example, I have a simple generated CRUD program that implements the PagedList package. This CRUD program needs to have multiple filters (10+). Previously, I have been passing the parameters through the URL.

Simple example:

// GET: Action/rows
[HttpGet]
public async Task<ActionResult> Index(int? page, string currentrowId, string rowId)
{
    if (rowId != null)
    {
        page = 1;
    }
    else
    {
        rowId = currentRowId;
    }
    var data = from s in db.tblrows
               where s.rowId.ToString().Contains(rowId)
               select s;

    int pageSize = 10;
    int pageNumber = (page ?? 1);

    ViewBag.Page = page;
    ViewBag.currentrowId = rowId;

    return View(await data.ToPagedListAsync(pageNumber, pageSize));
}

Then, in my view, I maintain my parameters by passing them through the URLs in each CRUD view. For example, in my index view I can open an item in the edit view using the following:

@Html.ActionLink("Edit", "Edit", new { id = item.rowId, page = ViewBag.Page, currentrowId = ViewBag.currentrowId }, new { @class = "btn btn-success btn-sm" })

In the edit view, I have similar code that maintains the current parameter so that when the user returns to the CRUD interface, their parameters are intact.

This way works fine for a few parameters, but it seems extremely tedious for many parameters. I considered creating a model for my search parameters and passing it as part of my ViewModel, but this didn't seem very efficient either when considering what that would require.

Any documentation or suggestions on a better way would be appreciated.

EDIT: Since this is MVC and I am using a GET action method, I cannot pass an object to the method.

You can pass objects to MVC actions using HttpGet....here is an example from live code we have in our solution....I changed the objects and removed our implementation, but it is definitely possible. The [FromUri] is what tells the model binder to work with complex objects in get requests.

        [HttpGet]
        [Route("orderitems")]
        public DataResponse<List<ItemDTO>> GetItems([FromUri]SearchObject search)
        {
             // Do stuff
        }

You can pass an object as parameter. It's a technique used when you have a large number of parameters.

See more details here:

https://www.includehelp.com/dot-net/how-to-pass-object-as-argument-into-method-in-c-sharp.aspx

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