gpt4 book ai didi

C# MVC 返回 View (对象)导致查询字符串?

转载 作者:行者123 更新时间:2023-11-30 19:48:28 25 4
gpt4 key购买 nike

我有这个 actionresult 方法:

public ActionResult MenuItemCreated(MenuItem item)
{
return View(item);
}

这是我的观点:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MenuItem>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
MenuItemCreated
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>MenuItemCreated</h2>

<%: Model.Caption %> is created succesfully
</asp:Content>

我在页面上看到的是正确的(测试创建成功)。但是我的查询字符串看起来像这样:

http://localhost:62602/Admin/MenuItemCreated/2?Caption=test&Link=%2Fclient

编辑:从此方法调用 ActionResult:

public ActionResult CreateMenuItem(FormCollection fc)
{
MenuItem menuItem = CreateMenuItemFrom(fc);
SaveMenuItem(menuItem);

return RedirectToAction("MenuItemCreated", menuItem);
}

编辑二:

对应 View :

<% using (Html.BeginForm("CreateMenuItem","Admin",FormMethod.Post)) {%>
<%: Html.ValidationSummary(true) %>

<fieldset>
<legend>Fields</legend>

<div class="editor-label">
<%: Html.LabelFor(model => model.Caption) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Caption) %>
<%: Html.ValidationMessageFor(model => model.Caption) %>
</div>

<div class="editor-label">
<%: Html.LabelFor(model => model.Link) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Link) %>
<%: Html.ValidationMessageFor(model => model.Link) %>
</div>

<div class="editor-label">
<%: Html.LabelFor(model => model.ParentId) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.ParentId) %>
<%: Html.ValidationMessageFor(model => model.ParentId) %>
</div>

<p>
<input type="submit" value="Create MenuItem" />
</p>
</fieldset>

<% } %>

这是为什么?我不想显示查询字符串。

最佳答案

问题出在下面一行:

return RedirectToAction("MenuItemCreated", menuItem);

执行重定向时,您不能像这样传递复杂的对象。只有简单的标量属性:

return RedirectToAction("MenuItemCreated", new {
id = menuItem.Id
});

然后在您要重定向的操作中获取给定 id 的相应菜单项模型:

public ActionResult MenuItemCreated(int id)
{
var menuItem = _someRepository.GetMenuItem(id);
...
}

关于C# MVC 返回 View (对象)导致查询字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5510856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com