0

我正在使用 jQuery Mobile 构建网站。其中一个页面是一个局部视图<div id="page13">,它有一个要发送到使用 Ajax.BeginForm 设置的服务器的简单表单。服务器上的操作方法更新数据库中的值。

原来的局部视图应该被替换为新版本的<div id="page13">.

实际发生的是在旧版本<div id="page13">之后插入新版本。

如何用新页面替换页面?

看法

<div data-role="page" data-theme="a" id="page13">
<div data-role="content">
    <div>
    @using (Ajax.BeginForm("ReinstateAlarms", "Mobile", new { EntityId = ViewBag.EntityId }, new AjaxOptions { UpdateTargetId = "page13", InsertionMode = InsertionMode.Replace, HttpMethod = "Post" }, new { }))
    {
        @Html.AntiForgeryToken()
        <label for="">Reinstate Alarms</label>
        <button type="submit" value="Search" >Submit</button>
    }
    </div>
<div data-theme="a" data-role="footer" data-position="fixed" data-id="footer-div" class="footer-div" >
<div data-role="navbar">
    <ul>
        <li><a href="#page1" data-transition="fade" data-icon="home">Final Home</a></li>
        <li><a href="#page4" data-transition="fade" data-icon="grid">Panel</a></li>
    </ul>
</div>

实际表格标签

<form action="/m/ReinstateAlarms/9665" data-ajax="true" &#39;slideup&#39;, true, false);" data-ajax-method="Post" data-ajax-mode="replace" data-ajax-update="#page13" id="form1" method="post">

控制器

    public ActionResult PanelAlarms(string EntityId)
    {
        return PartialView("~/Views/Mobile/Partial/PanelAlarms.cshtml");
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult ReinstateAlarms(string EntityId)
    {
        //Do some databse stufff
        return PanelAlarms(EntityId);
    }
4

1 回答 1

0

这是我完成提交表单并使用更新版本刷新页面的方式。

我使用了常规的<form>,而不是 Ajax.BeginForm()。data-ajax 必须设置为 false。

形式

<form id="meterForm" data-ajax="false">
      @Html.AntiForgeryToken()
      <label for="MeterReadingHours">Update Meter Reading</label><br />
      <input type="number" aria-valuemin="1" aria-required="true" name="MeterReadingHours" />
      <button type="submit" value="Update" >Update</button>
</form>

然后使用jquery绑定一个函数来提交表单。e.preventDefault();阻止表单提交。设置一个常规的$.post() 函数来提交表单。然后在响应中,使用$().load()<div data-role="content">从任何 ActionResult 创建原始版本中获取新版本。load() 允许您指定要插入的远程文档的一部分。这里我们只需要内容div,所以我们div[data-role="content"]在URL后面指定。

如果你停在这里,并运行脚本一切都会工作 - 但新的内容 div 将显示为纯文本,没有应用 jquery 样式。要强制更新,请将函数传递给$('#page15').trigger('create');.load() 的完整属性。这将导致新插入的元素被 jQuery 初始化。

脚本

$(document).ready(function () {
$('#meterUpdateForm').bind('submit', function (e) {
    e.preventDefault();
    $.post(
        '@Url.Action("MeterReadingUpdate", "Mobile", new { EntityId = ViewBag.EntityId })',
        $(this).serialize(),
        function (response) {
            $('#page15 div[data-role="content"]').load(
                 '@Url.Action("MeterReading", "Mobile", new { EntityId = ViewBag.EntityId }) div[data-role="content"]', 
                 function () {
                     $('#page15').trigger('create');
                 });
             });
         });
     });
 });
于 2013-04-11T18:09:17.250 回答