gpt4 book ai didi

javascript - $.post 不刷新 View MVC Asp.net

转载 作者:行者123 更新时间:2023-11-28 08:05:29 25 4
gpt4 key购买 nike

该 View 有 2 个 div。一个 div 显示文本框。另一个根据 Model.Flag 值显示文本。 On$post 当我调试时,我根据需要得到了内部和外部 html(带有第二个 div 文本)。但返回的 View 只有文本框值,没有其他 div 值。由于变量 (jq) 具有正确的数据,有人可以说我是否必须在 $.post 成功时通过 document.write 之类的东西重写 HTML 吗? View 是:

<% using (Html.BeginForm())
{
%>
<div>
The test message is <%= @Html.TextBox("Testname",Model.Testname) %>
</div>
<%
if (Model.Flag)
{ %>
<div>
Print this as true
</div>
<%} %>
<input type ="button" value ="ClickChange" id="btnChange" />
<% } %>

$(function()
{
$("#btnChange").click(function()
{
alert("clicked");
$.post("/Display/DisplayAgain/", { Testname: $("#Testname").val() },
function(data)
{
alert("success");
var jq = jQuery(data);
});
});

});

Controller 是:

public ActionResult FirstDisplay()
{
TestWierd.ViewModels.DisplayViewModel dispModel = new
TestWierd.ViewModels.DisplayViewModel();
return View("Details",dispModel);
}

public ActionResult DisplayAgain(TestWierd.ViewModels.DisplayViewModel dispModel)
{
dispModel.Flag = true;
return View("Details", dispModel);
}

我知道 $,post 会刷新整个 View ,但这并没有发生。难道我的理解不正确。当我调试 View 时,我得到的 Model.Flag 为 true,当我通过调试 javascript 将监视添加到变量 jq 时,我得到了具有所需 HTML 的内部 HTML 和外部 HTML,即文本框及其由用户输入的值以及HTML“将此打印为 true”,但在浏览器上我只看到 texbox 及其值,但看不到另一个带有文本“将此打印为 true”的 div。 难道我做错了什么。我可以不使用 $.post 检查模型值并显示文本吗?只需要在服务器端刷新 View 吗?请帮忙。

最佳答案

如果变量 $jq 中有想要显示的内容,您需要更新所需div的内容。

向 div 添加 Id,以便您可以轻松引用它

<div id="Message">
The test message is <%= @Html.TextBox("Testname",Model.Testname) %>
</div>

然后设置内容

//if the content is html then
$("#Message").html($jq);

//if the content is text (special characters like <> will be escaped automatically)
$("#Message").text($jq);

请注意,如果您想保留句子的其余部分,可以使用带有 id 的 span...

<div>
The test message is <span id="Message">
<%= @Html.TextBox("Testname",Model.Testname) %>
</span>
</div>

进一步解释...所有 AJAX 方法( $.ajax$.get$.post 等)都会导致浏览器打开与服务器的连接并读取响应,但是,它们都不会更新页面自动地。如果你想引起全页刷新,你可以使用表单和 submit it 。 Ajax 方法只是将响应作为变量提供(无论是文本、作为字符串的 html 还是从 json 构建的复杂对象),并让您随心所欲地使用它(覆盖、追加、在 javascript 中使用它来更新许多不同的内容) ui 组件等)。

因此,使用 Ajax 与使用 json 对象响应的服务通信通常更简单

{
"TestMessage": "Some test message",
"AnotherMessage": "Here I am"
}

或者仅使用您想要替换的页面部分(例如省略 <html><body> 等)

An <span style="font-weight:bold;">Html</span> message to be injected into the page

如果您想从 Asp.Net Mvc Controller 返回 Json,请参阅 this question

关于javascript - $.post 不刷新 View MVC Asp.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24832875/

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