我目前在控制器中有一个方法,它接受表单集合,保存数据,然后在"详细信息"页面中显示数据.目前,代码看起来像:

[HttpPost]
public ActionResult Create(PersonModel person)
{
    if (person.IsValid())
    {
        person.additionalData = "Person created successfully";
        return View("Details", person);
    }
}

问题是,以这种方式返回Details视图会保留URL mysite/Person/Create——理想情况下,我希望URL是mysite/Person/Details/{PersonId}.

我相信这一定是可能的.显然,我需要回应.重定向,但是这不允许我将模型传递给视图.据我所知,我不能通过使用RedirectToAction的模型?

谢谢你的帮助.

编辑:确认-创建操作生成的模型与详细信息操作创建的默认模型不同.因此,直接重定向到Action并传递ID不起作用,因为生成的模型不正确.为了提供更多上下文,Create操作中的模型包含一个附加值,说明‘Person Created Successful’,如果我重定向到Details操作,此消息不会出现在模型中.

推荐答案

直接从我自己的应用程序:

public ActionResult Create(Booking item)
{
    if (ModelState.IsValid)
    {
        int newID = _tasks.Create(item);
        // NEW section to emulate model being populated for use in Details view
        TempData["additionalData"] = "Person created successfully";
        return RedirectToAction("Details", new { id = newID });
    }
    else
    {
        return View();
    }
}

那么,你的"细节"行动不能是这样的吗:

public ActionResult Details(int id)
{
    var item = _tasks.GetByKey(id);
    var additionalData = TempData["additionalData"];
    if(item != null) {
        if(additonalMessage!=null)
        {
            item.additionalData = additionalData;
        }
        return View(item);
    }
    else
        return View("Notfound");
}

你不能采取类似的方法吗??

您可以按照约定执行重定向,并设置一个标志(在tempdata上,如上所述)来给出此消息吗?tempadata标志只会在创建操作中设置,因此只会在创建新的"person"对象时发生.因此,"细节"操作只能作为"创建"操作的结果来显示它

Asp.net相关问答推荐

Web API Queryable - 如何应用 AutoMapper?

asp.net、url 重写模块和 web.config

更改 GridView 中列的标题文本

防止 asp.net Web 表单中的跨站点请求伪造 (csrf) 攻击

相当于服务器端的 ASP.NET 包括

IIS 7.5 上没有 asp.net 功能

发布发布事件

在 IIS 上托管 ASP.NET 5 项目

为什么 Asp.Net Identity IdentityDbContext 是一个黑盒?

在不知道键名的情况下访问 JSON 对象的元素

如何从 JS 访问 ViewBag

防止在 Visual Studio 2008 ASP.NET Web 窗体中复制粘贴时自动生成 ID

如何使用 asp.net 获取 html Select 的选定值

存在 ios 7 虚拟键盘时,div 元素不会停留在底部

显示 ModalPopupExtender 时如何指定要运行的 javascript

如何防止aspxerrorpath作为查询字符串传递给 ASP.NET 自定义错误页面

不同域的登录页面

IISExpress 找不到使用 Visual Studio 2013 运行 localhost 的 ssl 页面

将 html 标记从 jquery 发布调用发送到 asp.net 页面时,从客户端检测到潜在危险的 Request.QueryString 值

在 ASP.NET MVC 中模拟 User.Identity