c# - 重新发送模型会重置 asp.net mvc 中的值吗?

标签 c# asp.net-mvc

这是我的观点:

@model test2.Models.ChatModel
@{
    ViewBag.Title = "Channel";
    Layout = "~/Views/Shared/_Layout.cshtml";

}

<center>
    <h2>Channel: @Model.channelName</h2>

    @{
        foreach (string line in Model.chatLog) {
            <div>@line</div>
        }     
    }

    <br />

    @using (Html.BeginForm("sendMessage", "Home", FormMethod.Post)) {
        @Html.TextBoxFor(model => model.message)
        <button type="submit"> Send Message </button>
    }

</center>

这是我的 Controller :

public ActionResult sendMessage(ChatModel model) {

            //send message somewhere

            //this is not working
            return RedirectToAction("Channel", "Home", new { channel = model.channelName });

            //this is working
            return RedirectToAction("Channel", "Home", new { channel = "test" });
}

错误发生在 redirectToAction 方法中。不知何故“model.channelName”为空,但在我看来@Model.channelName 正确显示了 channel 名称。

看起来当您将模型发送到 View ,并将该模型“重新发送”回 Controller 时,信息丢失了。

有什么简单的方法可以解决这个问题吗?

附言一步一步:

  1. 模型获取 channel 名称
  2. 模型已发送给观众
  3. View 正确显示来自模型的数据
  4. 向模型添加消息
  5. 将模型发送到 Controller
  6. 模型不包含第 1 步的信息

最佳答案

您需要在表单中包含 model.channelName。尝试添加:

@Html.HiddenFor(model => model.channelName)

任何未通过表单发布的内容在您的模型(包括您的聊天记录)中都将为空

关于c# - 重新发送模型会重置 asp.net mvc 中的值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48863857/

相关文章:

c# - 如何优化我的 BinaryWriter?

c# - 如何从 Web 应用程序在多个客户端上远程执行程序?

asp.net-mvc - ASP.NET MVC 4 拦截所有传入请求

c# - 在 MVC 6 中将 View 渲染为字符串

c# - 如何在静态方法中使用 Controller 类的 Response 属性?

c# - 使用 Moq 调用原始方法

c# - Quaternion.Slerp 在没有 Y 轴的 X 和 Z 轴上

c# - C#翻转位图函数

c# - HTML &lt;textarea&gt; 仅将 '\n' 发送回服务器

c# - 使用 Html Helper 在创建的 TextBox 元素中添加新的 html 属性