是否有可能重定向到另一个动作,将其作为HttpPost传递给我们当前的模型

本文关键字:我们 模型 HttpPost 重定向 有可能 另一个 是否 | 更新日期: 2023-09-27 18:00:55

因此,我正在试验ASP.NET MVC,我有以下代码:

public class TrollController : Controller
{
    public ActionResult Index()
    {
        var trollModel = new TrollModel()
                                    {
                                        Name = "Default Troll", 
                                        Age = "666"
                                    };
        return View(trollModel);
    }
    [HttpPost]
    public ActionResult Index(TrollModel trollModel)
    {
        return View(trollModel);
    }
    public ActionResult CreateNew()
    {
        return View();
    }
    [HttpPost]
    public ActionResult CreateNew(TrollModel trollModel)
    {
        return RedirectToAction("Index");
    }
}

这个想法是有一个索引页面,显示我们的巨魔的年龄和他的名字。

有一个操作允许我们创建一个巨魔,在创建它之后,我们应该回到索引页面,但这次是使用我们的数据,而不是默认的数据。

有没有办法将TrollModel CreateNew(TrollModel trollModel)正在接收的信息传递给Index(TrollModel trollModel)?如果是,如何?

是否有可能重定向到另一个动作,将其作为HttpPost传递给我们当前的模型

最好的方法是将troll保存在服务器上的某个位置(数据库?(,然后在重定向时只将id传递给索引操作,以便它可以取回它。另一种可能性是使用TempData或Session:

[HttpPost]
public ActionResult CreateNew(TrollModel trollModel)
{
    TempData["troll"] = trollModel;
    return RedirectToAction("Index");
}
public ActionResult Index()
{
    var trollModel = TempData["troll"] as TrollModel;
    if (trollModel == null)
    {
        trollModel = new TrollModel
        {
            Name = "Default Troll", 
            Age = "666"
        };
    }
    return View(trollModel);
}

TempData将仅在一次重定向后存活,并在后续请求中自动收回,而Session将在会话的所有HTTP请求中持久存在。

还有一种可能性是在重定向时将troll对象的所有属性作为查询字符串参数传递:

[HttpPost]
public ActionResult CreateNew(TrollModel trollModel)
{
    return RedirectToAction("Index", new  
    {  
        Age = trollModel.Age, 
        Name = trollModel.Name 
    });
}
public ActionResult Index(TrollModel trollModel)
{
    if (trollModel == null)
    {
        trollModel = new TrollModel
        {
            Name = "Default Troll", 
            Age = "666"
        };
    }
    return View(trollModel);
}

现在,您可能需要重命名Index POST操作,因为不能有两个具有相同名称和参数的方法:

[HttpPost]
[ActionName("Index")]
public ActionResult HandleATroll(TrollModel trollModel)
{
    return View(trollModel);
}

在CreateNew中必须有某种持久性,例如troll可能保存在数据库中。它还必须有某种ID。因此Index方法可以更改为

public ActionResult Index(string id)
{
    TrollModel trollModel;
    if (string.IsNullOrEmpty(id))
    {
        trollModel = new TrollModel()
                                {
                                    Name = "Default Troll", 
                                    Age = "666"
                                };
    }
    else
    {
        trollModel = GetFromPersisted(id);
    }
    return View(trollModel);
}

以及在CreateNew 中

[HttpPost]
public ActionResult CreateNew(TrollModel trollModel)
{
    return RedirectToAction("Index", new {id = "theNewId"});
}