Jourmand
Jourmand

Reputation: 948

Pass List<Object> from Razor View To Post Action

I have model View like This:

public class ContactHomePage
{
    public string Query { get; set; }
    public List<SqlParameter> SqlParameters { get; set; }
}

In Index action (that works as HTTPGet) I fill ContactHomePage and passed to View, and in the view, I want to pass this model to action GetRecords, this post action like this:

public async Task<IActionResult> GetRecords(JqGridRequest request, string query, List<SqlParameter> sqlParameters)
{
}

and my ajax post url like this:

url: '@Url.Action("GetRecords", "Contact", new { query = Model.Query, sqlParameters = Model.SqlParameters})'

in running the app, query object that was in string mode has its data but sqlParameters with type List hasn't any value! now my question is, how can post List<Object> from razor view to post action?

Upvotes: 1

Views: 1467

Answers (1)

solrac
solrac

Reputation: 629

If your ActionResult is type of Get, you can't sent complex data types. A solution is convert your complex object (Model.SqlParameters) to string, using Newtonsoft.Json.JsonConvert, and then parse it on ActionResult to your object. Something like this:

At razor view (Newtonsoft.Json.JsonConvert.SerializeObject):

@Url.Action("MyActionResult", "MyController", new { objectStringfied = Newtonsoft.Json.JsonConvert.SerializeObject(new List<MyObject>()) })

At controller (Newtonsoft.Json.JsonConvert.DeserializeObject):

public virtual ActionResult MyActionResult(string objectStringfied)
{
     List<MyObject> model = Newtonsoft.Json.JsonConvert.DeserializeObject<List<MyObject>>(objectStringfied);

     // ...
}

Upvotes: 2

Related Questions