Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using RedirectToAction with custom type parameter

asp.net mvc 2

I have this action in Identity controller

public ActionResult Details(string id, MessageUi message)
{

And I'm trying to redirect to this action from another controller, but I don't know how should I pass the message parameter

I was trying with

    var id = "someidvalue"
    var message = new MessageUi("somevalue");
    return RedirectToAction("Details", "Identity", new { id, message});
}

but message parameter is null

like image 739
Rodrigo Juarez Avatar asked Mar 02 '26 11:03

Rodrigo Juarez


1 Answers

That's normal. You cannot pass complex objects in urls when redirecting and that's the reason why the MessageUi object is not received. Only scalar properties which will be translated into &-separated key/value pairs in the url.


One possibility would be to pass all the simple properties of this object so that the default model binder can reconstruct it at the target location:

var id = "someidvalue"
var message = new MessageUi("somevalue");
return RedirectToAction("Details", "Identity", new { 
    id = id, 
    MessageProp1 = message.MessageProp1,
    MessageProp2 = message.MessageProp2,
    MessageProp3 = message.MessageProp3,
});

You could also pass only a message id:

var id = "someidvalue";
return RedirectToAction("Details", "Identity", new { 
    id = id, 
    messageId = "somevalue"
});

and have the message object being reconstructed in the details action using this id:

public ActionResult Details(string id, string messageId)
{
    var message = new MessageUi(messageId);
    ...
}

and this job could be greatly done by a custom model binder for the MessageUi type.


Another possibility would be to use TempData or Session:

var id = "someidvalue";
TempData["message"] = new MessageUi("somevalue");
return RedirectToAction("Details", "Identity", new { id });

and then inside the Details action:

var message = TempData["message"] as MessageUi;
like image 96
Darin Dimitrov Avatar answered Mar 07 '26 02:03

Darin Dimitrov