.NET 8 MVC object looses values when passed to another function in an MVC controller

Richard Scannell 426 Reputation points
2024-10-25T15:05:52.84+00:00

I am trying to pass a variable to another function in .NET core 8 , but the variable passed loses values on the way. Does anyone have any clues about why this might be?

Search class

public class DB_Search:IValidatableObject

{

public string Field1 { get; set; }

public string Field2 { get; set; }

}

IndexWithSearch function in Controller

[ActionName("IndexWithSearch")]

public async Task<ActionResult> Index(DB_Search search)

{

// do stuff to process search

}

Address bar search MyController/IndexWithSearch?search.Field1="Aardvark" works IE the Index function opens & the column Field1 contains "Aardvark"

When I pass it from another controller

DB_Search item = new DB_Search();

item.Field1="Aardvark";

return RedirectToAction("IndexWithSearch", new { search = item });

Debugger shows me opening IndexWithSearch , with an object called search of type DBSearch, but its search.Field1 column is null

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | C#
{count} votes

Accepted answer
  1. Anonymous
    2024-10-28T07:54:11.79+00:00

    Hi @Richard Scannell,

    You can directly pass the object route value like below:

    DB_Search item = new DB_Search();
    item.Field1="Aardvark";
    return RedirectToAction("IndexWithSearch",item);   //change here...
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Rena

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2024-10-25T16:05:55.77+00:00

    Redirect query strings only support simple values, that is a string or number. It converts the passed value to string, so objects with properties don’t work (the ToString() returns the class name).

    you should make a new get action that passes the search fields as separate parameters that the redirect can use.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.