还有人在使用 MVC3、JQuery 1.7.1 和 JQuery Mobile 1.1.0 时遇到问题吗?每当我提交标准 MVC 表单时,我的 URL 来自:
本地主机/站点/ Controller /操作
至
localhost/site/controller/action#/controller/action
我正在简化一个相当困惑的现有站点,因此我正在通过 Controller 清理并删除不需要的 jquery 表单处理,并且只使用 Razor。我想知道我的项目中是否存在冲突,但我已设法从新项目中复制它:
打开 VS2010,新建空 MVC3 项目 - 即下面未提及的所有内容都是默认的 MVC 项目
添加测试 Controller :
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class TestController : Controller
{
public ActionResult Testing()
{
return View(new TestModel());
}
[HttpPost]
public ActionResult Testing(TestModel testModel)
{
if (ModelState.IsValid)
{
//Temp for examples sake
ModelState.AddModelError("EmailAddress", "Account not found.");
}
return View();
}
}
}
添加测试模型:
using System.ComponentModel.DataAnnotations;
namespace MvcApplication1.Models
{
public class TestModel
{
[Required(ErrorMessage = "Email is required.")]
[DataType(DataType.EmailAddress)]
[StringLength(50, ErrorMessage = "Email too long.")]
public string EmailAddress { get; set; }
}
}
使用 View 测试添加 View 文件夹测试:
@model MvcApplication1.Models.TestModel
@using (Html.BeginForm("Testing", "Test", FormMethod.Post))
{
<div id="divForgotPassword">
<fieldset data-role="fieldcontain">
<legend>Forgot Password</legend>
<div id="editor-label">
<label for="txtLogonID">
Email Address:</label></div>
<div id="editor-field">
@Html.TextBoxFor(m => m.EmailAddress, new { type = "email" })
<br />
@Html.ValidationMessageFor(m => m.EmailAddress)</div>
<input type="submit" value="Reset Password" data-role="button" data-inline="true" />
</fieldset>
</div>
}
运行并访问http://localhost:65298/Test/Testing 点击重置密码,验证器工作,URL 不变
将 jquery.mobile-1.1.0.js 和 jquery-1.7.1.min.js 添加到脚本文件夹
在_Layout.cshtml中添加: 并将 jquery 1.5.1 更改为 1.7.1
运行并再次访问我们的页面 点击重置密码,验证器可以工作,但现在您拥有: http://localhost:65298/Test/Testing#/Test/Testing
我一定做错了什么?主要问题是,使用该 URL,我的其他 javascript 不喜欢运行。我还担心它会与其他东西发生干涉,而且它看起来很丑而且一定是错误的......
非常感谢!
最佳答案
如上所述,通过ajax加载页面是jQm的默认行为。使用 rel="external"
确实适用于链接,但它实际上适用于移动应用范围之外的链接(例如访问“主要”非- 托管在同一域上的移动网站),并且它不适用于表单提交。对于移动应用和/或表单提交范围的各个链接,建议添加属性 data-ajax="false"
。
因此,对于单个链接,您可以这样做:
<a href="/nonMobileHome" rel="external">Full website (non-mobile)</a>
<a href="/user/edit/5" data-ajax="false">Load mobile page without ajax</a>
对于表单提交,请使用:
<form action="/user/edit/5" method="post" data-ajax="false">
对于页面上的所有链接/表单,请在加载 jQuery Mobile 之前将此 JavaScript 添加到您的页面:
$(document).bind("mobileinit", function () { $.mobile.ajaxEnabled = false; });
我发现在 ASP.NET MVC 中最简单的方法是全局禁用 jQm 的 ajax 加载行为,方法是将上面的 javascript 语句包含在站点范围的 js 文件中。不幸的是,这个问题在 MVC4 和 Visual Studio 2012 中仍然存在,尽管 Microsoft 默认包含 jQuery Mobile MVC4 模板。
有关在 jQuery Mobile 中抑制 ajax 加载的更多信息:
http://jquerymobile.com/test/docs/pages/page-links.html
http://jquerymobile.com/test/docs/forms/forms-sample.html
关于jquery - 添加 JQueryMobile 后 ASP MVC3 URL 出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10265026/