ASP.NET MVC我想重定向到另一个将我的模型传递给它的动作,以获得正确的URL

问题描述 投票:0回答:1

我想在验证错误后将模型传递给我的视图。为了执行此操作,我调用检查验证的操作:

    [HttpPost]
    [Authorize]
    public ActionResult CreateIncident(IncidentModel incident)
    {
        if (ModelState.IsValid)
        {
            string response = _incidentService.CreateIncident(incident).Value;
            if (response.Length == 15)
            {
                TempData["Message"] = String.Format($"Le ticket {response} a bien été réceptionné par l'équipe support");
                TempData["Class"] = "success";
            }
            else
            {
                TempData["Message"] = "Une erreur est survenue lors de la création de l'incident";
                TempData["Class"] = "warning";
            }

            return RedirectToAction("Index");
        }

        TempData["Message"] = "Attention, vous n'avez pas saisi toutes les informations requises.";
        TempData["Class"] = "warning";

        return View("Index", incident);
    }

如果验证错误,应该将我的模型发送回我的视图:

    [Authorize]
    public ActionResult Index()
    {
        ViewBag.Title = "Karanga";
        return View("Index", new IncidentModel());
    }

对于同一个视图,我发布了我的模型。

这里的问题是当我调用Index()时我的URL是/ Incident / Index(默认路由),一切都很好。但后来我调用了CreatIncident(),我的URL变成了/ Incident / CreateIncident。我真的需要它是正确的,因为我使用它来设置活动菜单按钮,例如。

我尝试重定向到动作索引,希望我的模型可以存储在缓存中,但如果它已经工作,我不会在这里寻求帮助。

是否可以将我的模型作为参数重定向?

如果您对我如何解决这个问题有任何想法,可以通过重定向到动作索引,最好不要在TempData中传递我的模型(但如果没有其他解决方案,我会这样做),它会有所帮助。

asp.net asp.net-mvc asp.net-mvc-4 asp.net-mvc-5
1个回答
0
投票

你能让你的Index方法做双重任务吗?像这样的东西:

[HttpPost]
[Authorize]
public ActionResult Index(IncidentModel incident = null)
{
    if (incident == null) {
        ViewBag.Title = "Karanga";
        return View("Index", new IncidentModel());
    }

    if (ModelState.IsValid)
    {
        string response = _incidentService.CreateIncident(incident).Value;
        if (response.Length == 15)
        {
            TempData["Message"] = String.Format($"Le ticket {response} a bien été réceptionné par l'équipe support");
            TempData["Class"] = "success";
        }
        else
        {
            TempData["Message"] = "Une erreur est survenue lors de la création de l'incident";
            TempData["Class"] = "warning";
        }

        return RedirectToAction("Index");
    }

    TempData["Message"] = "Attention, vous n'avez pas saisi toutes les informations requises.";
    TempData["Class"] = "warning";

    return View("Index", incident);
}

然后您的表单操作将是:

@using(Html.BeginForm("Index")) {
...
}

在我们想要发布数据但不重新加载屏幕的应用程序中,我们将获取表单数据,并使用JavaScript帖子将其发送到服务器。然后在客户端页面未更改或重新加载时使用最新数据更新服务器。

这还允许您以Json的形式从服务器检索结果,并根据需要更新任何表单字段或只读/值。

© www.soinside.com 2019 - 2024. All rights reserved.