简体   繁体   中英

Passing List of String type with RedirectToAction in ASP.NET-MVC

This code is used to pass a List<String> with RedirectToAction method:

public List<String> ListOfBrandNames(string id)
    {
        var result = db.Items.Where(x => x.Category.Name.Equals(id)).Select(x => x.BrandID).ToList();
        var ListOfBrands = db.Brands.Where(t => result.Contains(t.BrandID)).ToList();
        List<String> BrandNames = ListOfBrands.Select(f => f.Name.ToString()).ToList();
        return RedirectToAction("BrandsOfACategory", new { brands = BrandNames });
    }

RedirectToAction method is throwing this error:

Cannot implicitly convert type 'System.Web.Mvc.RedirectToRootResult' to 'System.Collection.Generic.List'

You're using wrong return type on the action method, since RedirectToAction requires return type of ActionResult instead of List<string> because RedirectToRouteResult inherited from ActionResult .

Update:

You need to serialize the list into JSON string to pass it smoothly (with Newtonsoft.Json library), so the target action method must use string parameter. Here is the correct setup to send list of brands to another action method:

public ActionResult ListOfBrandNames(string id)
{
    var result = db.Items.Where(x => x.Category.Name.Equals(id)).Select(x => x.BrandID).ToList();
    var ListOfBrands = db.Brands.Where(t => result.Contains(t.BrandID)).ToList();
    return RedirectToAction("BrandsOfACategory", new { brands = JsonConvert.SerializeObject(ListOfBrands) });
}

And the target controller action should be look like this:

[HttpGet]
public ActionResult BrandsOfACategory(string brands)
{
    var listOfBrands = JsonConvert.DeserializeObject<List<Brand>>(brands);

    List<string> BrandNames = listOfBrands.Select(f => f.Name.ToString()).ToList();

    // do something and return view
}

Reference:

How to pass List in Redirecttoaction

Try with below code,

public List<String> ListOfBrandNames(string id)
{
    var result = db.Items.Where(x => x.Category.Name.Equals(id)).Select(x => x.BrandID).ToList();
    var ListOfBrands = db.Brands.Where(t => result.Contains(t.BrandID)).ToList();
    List<String> BrandNames = ListOfBrands.Select(f => f.Name.ToString()).ToList();
    TempData["Brands"]=BrandNames;
    return RedirectToAction("BrandsOfACategory");
}

After then you can fetch data from TempData to list of string in "BrandsOfACategory" method.

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