开发者

Using RedirectToAction with custom type parameter

开发者 https://www.devze.com 2023-02-13 06:31 出处:网络
asp.net mvc 2 I have this action in Identity controller public ActionResult Details(string id, 开发者_StackOverflowMessageUi message)

asp.net mvc 2

I have this action in Identity controller

public ActionResult Details(string id, 开发者_StackOverflowMessageUi 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


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消