Как я могу передать свой объект с RedirectToAction? - PullRequest
0 голосов
/ 13 февраля 2019

У меня есть действие SubmitComment и класс Message.Я хочу использовать Message класс для отправки, если действие выполнено успешно или нет, но Message.Result имеет значение false и Message.Text равно нулю, когда я проверяю их в действии ShowProduct.

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

Мое SubmitCommen т Действие:

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);
}

В чем проблема?

Ответы [ 2 ]

0 голосов
/ 14 февраля 2019

Для 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");
}
.
0 голосов
/ 13 февраля 2019

Вы не можете передать объект с 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);
...