【问题标题】:How can I pass my object with RedirectToAction?如何使用 RedirectToAction 传递我的对象?
【发布时间】:2019-02-13 12:23:02
【问题描述】:

我有一个SubmitComment Action 和一个Message 课程。我想使用Message 类来发送操作是否成功完成,但是当我在ShowProduct 操作中检查它们时,Message.Result 是假的,Message.Text 是空的。

public class Message
{
    public bool Result { get; set; }
    public string Text { get; set; }
}

我的SubmitComment 操作:

public ActionResult SubmitComment(int productId, string comment, string nickName)
{
        try
        {
            var productCM = new ProductCM
            {
                //I make my prodcut comment object here
            };
            storesDB.ProductCMs.Add(productCM);
            storesDB.SaveChanges();

            Message message = new Message
            {
                Result = true,
                Text = "Your comment successfully registered."
            };

            return RedirectToAction("ShowProduct", new { id = productId, message });
        }
        catch (//if any exeption happend)
        {
            Message message = new Message
            {
                Result = false,
                Text = "Sorry your comment is not registered."
            };

            return RedirectToAction("ShowProduct", new { id = productId, message });
        }
}

我的ShowProduct 行动:

public ActionResult ShowProduct(int? id, message)
{
    ViewBag.Message = message;

    var model = storesDB.Products;

    return View(model);
}

有什么问题?

【问题讨论】:

  • catch (//if any exeption happend) -> catch (Exception ex) 或简单的catch (Exception)
  • 有什么问题,你得到的是 id 和 message 的空值还是仅仅为 message。尝试使用 RouteValueDictionary 来传递复杂的对象。
  • 是的,我认为我应该更好地使用 RoutValueDictionary @hazimdikenli
  • 是的,我认为我应该更好地使用 RoutValueDictionary @Mikev

标签: c# asp.net-core asp.net-core-routing


【解决方案1】:

您不能使用RedirectToAction 传递对象。或者,代替return RedirectToAction("ShowProduct", new { id = productId, message }) 使用return ShowProduct(productId,message);,如下所示:

Message message = new Message
{
    Result = true,
    Text = "Your comment successfully registered."
};

return ShowProduct(productId,message);

【讨论】:

  • 它有效,但我想在提交评论后显示 ShowProduct 视图,但它想显示 SubmitComment 视图!!!你能帮忙吗?
  • @FarshadShahsavari 将其标记为答案,并更好地根据新要求明确提出不同的问题。我会尽力帮助你。
【解决方案2】:

对于RedirectToAction,它会将参数作为查询字符串传递,您无法传递嵌入对象。

尝试指定属性,如

return RedirectToAction("ShowProduct", new { id = productId, message.Result, message.Text });

对于return ShowProduct(productId,message);,指定ViewName 像

public ActionResult ShowProduct(int? id, Message message)
{
    ViewBag.Message = message;

    return View("ShowProduct");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多