【问题标题】:ASP.NET MVC ViewBag values not being displayed in view after Ajax callASP.NET MVC ViewBag 值在 Ajax 调用后未显示在视图中
【发布时间】:2021-11-19 18:29:02
【问题描述】:

我有以下视图和控制器代码:

索引.cshtml

@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <span style="color:green; font-weight:bold;" id="Message">@ViewBag.Message</span>
    <input type="text" id="txtMessage" />
    <input type="submit" id="btnSubmit" value="Submit" />
}
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script type="text/javascript">

    $('#btnSubmit').click(function (event) {
       
        $.ajax({
            type: "POST",
            url: "/Home/Create",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            async: false,
            data: JSON.stringify({
                'message': $('#txtMessage').val()
            })
        });

    });
</script>

控制器代码:

public class HomeController : Controller
{
    public ActionResult Index(string message)
    {
        return View();
    }
    
    [HttpPost]
    public ActionResult Create(string message)
    {
        ViewBag.Message = message;

        return View("Index");
    }
}

单击按钮并进行 ajax 调用后,我无法在索引视图中看到 Create 方法中设置为 ViewBag.Message 的消息。

【问题讨论】:

    标签: ajax asp.net-mvc viewbag


    【解决方案1】:

    如果您使用 Begin 表单和按钮类型作为提交,那么为什么要编写 ajax 方法?

    从 javascript 代码中删除您的 btnSubmit 点击并使用文本框作为 TextBoxFor,

    @Html.TextBoxFor(m => m.message, new { @class = "form-control" })
    

    它应该可以工作。

    在没有强类型的情况下更新答案

    根据代码,您使用的是 Begin Form,因此不需要 ajax 调用。 因此,首先删除 javascript 代码,或者如果您保留该代码,则没有任何意义。

    现在需要更新以下行:

        <input type="text" id="txtMessage" **name = "txtMessage"** />
    

    并且在控制器代码发布方法中,以下名称应该相同。

    [HttpPost]
    public ActionResult Create(**string txtMessage**)
    {
        ViewBag.Message = **txtMessage**;
    
        return View("Index");
    }
    

    【讨论】:

    • 我没有使用强类型视图。
    • @MohanRaju 好的。所以根据代码,当你点击提交时,你的 Create post 方法中是否有调试?
    • 是的。在 Create post 方法中进行调试。
    • 好的。根据 ViewBag 的概念,它应该可以工作!您能否尝试使用 TempData["Message"] 语法。因为我已经为 TempData 使用了相同的结构并且它工​​作正常。
    • 我也尝试过使用 TempData,但没有成功。
    猜你喜欢
    • 1970-01-01
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    相关资源
    最近更新 更多