【问题标题】:$.post does not refresh the View MVC Asp.net$.post 不刷新 View MVC Asp.net
【发布时间】:2014-07-18 19:59:35
【问题描述】:

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

<% 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);
        });
    });

});

控制器是:

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

【问题讨论】:

  • 请添加您的 DisplayViewModel 代码

标签: javascript asp.net-mvc


【解决方案1】:

如果你在变量$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"
}

或仅使用您希望替换的页面部分(例如,省略 &lt;html&gt;&lt;body&gt; 等)

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

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

【讨论】:

  • 是的,使用了 Json。感谢一百万美元清除 $.post 的概念。任何 AJAX 方法都不会自动更新页面是有道理的,最简单的方法是使用 JSON
  • 很高兴,很高兴我能提供帮助。顺便说一句,如果您使用的是 Json,jQuery 可以在使用 $.getJSON 检索它时对其进行膨胀
猜你喜欢
  • 2019-09-12
  • 2013-02-10
  • 1970-01-01
  • 1970-01-01
  • 2011-02-04
  • 1970-01-01
  • 1970-01-01
  • 2012-01-04
  • 1970-01-01
相关资源
最近更新 更多