点击提交按钮时jQuery无法获取@Model.Id值的问题
解决AJAX提交表单时@Model.Id无法正确传递的问题
问题根源
按钮类型为submit,点击时会触发表单的默认提交行为:页面立即刷新,导致AJAX代码(包括alert弹窗)还未执行完成就被中断;同时默认提交请求与AJAX请求冲突,最终导致BlogId参数传递异常。
解决方案
1. 阻止表单默认提交行为
在按钮的点击事件中添加e.preventDefault(),中断默认提交流程,确保AJAX请求正常执行:
$(function () { $("#btnPostComment").click(function (e) { // 阻止表单默认提交动作 e.preventDefault(); alert(@Model.Id); var url = $("#formPostComment").attr("action"); var formData = new FormData(); // 改用name属性选择器,避免依赖id(原表单字段未设置id) formData.append("Name", $("input[name='name']").val()); formData.append("Email", $("input[name='email']").val()); formData.append("Comment", $("#message").val()); formData.append("BlogId", @Model.Id); $.ajax({ type: 'POST', url: url, data: formData, processData: false, contentType: false, success: function (response) { LoadPartialView(response.blogId); $('#formPostComment')[0].reset(); }, failure: function (response) { alert(response.responseText); }, error: function (response) { alert(response.responseText); } }); }); });
2. 改用button类型按钮
直接修改按钮的type属性为button,从根源上避免触发表单默认提交:
<button type="button" id="btnPostComment" class="btn btn-main m-bottom-40">Post Comment</button>
3. 额外优化:用隐藏字段存储BlogId(更稳妥)
在表单中添加隐藏字段存储@Model.Id,后续AJAX直接读取该字段值,避免重复编写服务器端表达式:
<form id="formPostComment" method="post" asp-controller="BlogData" asp-action="PostComment"> <!-- 新增隐藏字段存储BlogId --> <input type="hidden" id="hiddenBlogId" value="@Model.Id" /> <!-- 原有表单字段保持不变 --> <div class="row"> <div class="col-md-6"> <input type="text" placeholder="Name *" name="name" required> </div> <div class="col-md-6"> <input type="email" placeholder="Email *" name="email" required> </div> </div> <textarea name="message" placeholder="Message *" id="message" cols="45" rows="10" required></textarea> <button type="submit" id="btnPostComment" class="btn btn-main m-bottom-40">Post Comment</button> </form>
对应AJAX代码修改:
formData.append("BlogId", $("#hiddenBlogId").val());
验证效果
修改完成后,点击按钮不会触发页面刷新,alert弹窗正常显示,AJAX请求会正确携带BlogId参数,Controller断点中就能获取到正确的Id值。
内容的提问来源于stack exchange,提问作者nikhil
相关产品推荐
相关产品推荐

