[英]MVC unable to submit and save data from partial view using ajax.beginform
我是MVC的新手,但是我一直在对另一个小组创建的现有代码进行一些更改。
有一个带有几个局部视图的用户数据视图,我想更新“个人资料”部分(姓名,电话等)。 问题是单击“保存”按钮没有任何作用。 在控制器上设置断点甚至不会显示站点已到达该代码。
这些是当前代码的主要部分。
“用户详细信息”视图:
@model UserDetailsModel
@{
Layout = "~/Views/Shared/_ApplicationLayout.cshtml";
}
...
<h2>User Details</h2>
...
<hr />
<div class="row">
<div class="span2">
<ul class="nav nav-pills nav-stacked" id="js-side-nav" data-spy="affix">
<li class="active"><a href="#profile">Profile</a></li>
<li><a href="#userdevices">Functions</a></li>
...
</ul>
</div>
<div class="span10">
<ul class="unstyled">
<li id="profile">
<h3>Profile</h3>
@Html.Partial("_UserProfile", Model.ProfileModel)
<hr />
</li>
<li id="functions">
<h3>Functions</h3>
@Html.Partial("_UserFunctions", Model.FunctionsModel)
<hr />
</li>
...
“用户个人资料”部分视图:
//(我添加了HttpMethod =“ Post”)
@model UserProfileModel
<section id="user-profile-section">
@using (Ajax.BeginForm("UserProfile", "UserDetail", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "user-profile-section", InsertionMode = InsertionMode.Replace}))
{
@Html.EditorForModel("CustomForm")
<input class="btn btn-primary" type="submit" value="Save Profile"/>
}
</section>
“用户详细信息”控制器:
//(我添加了[System.Web.Http.HttpPost])
[System.Web.Http.HttpPost]
public ActionResult UserProfile(Guid userId, [FromBody] UserProfileModel model)
{
if(!Request.IsAjaxRequest())
throw new Exception("Expecting ajax request");
if(!ModelState.IsValid)
return PartialView("_UserProfile", model);
var service = new UserService();
WebUser user = service.GetUserProfile(userId, SessionState.ApplicationId);
Mapper.DynamicMap(model, user.Profile, model.GetType(), user.Profile.GetType());
service.UpdateUser(user);
return PartialView("_UserProfile", model);
}
“用户个人资料”模型:
using System.ComponentModel.DataAnnotations;
namespace UserDetail
{
public class UserProfileModel
{
[Required]
[Display(Name = "First Name")]
public string ContactFirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string ContactLastName { get; set; }
[Display(Name = "Business Phone")]
public string ContactBusinessPhone { get; set; }
...
在web.config上将ClientValidationEnabled和UnobtrusiveJavaScriptEnabled设置为TRUE。
我首先要使代码到达控制器中的UserProfile部分,以便可以确保service.UpdateUser()方法有效。 我已经检查,搜索并尝试了几种方法,但没有找到我所缺少的东西。 最后,显然,我希望能够更新数据。
谢谢。
我敢打赌,您的某些字段验证失败,但是它没有相应的验证消息或被隐藏,因此您看不到错误。 也许要进行测试,只需删除表单中除“提交”按钮之外的所有内容,然后查看它是否成功提交。
另一个作为故障排除步骤尝试的方法是更改(将其复制到注释以在测试后还原)
@using (Ajax.BeginForm("UserProfile", "UserDetail", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "user-profile-section", InsertionMode = InsertionMode.Replace}))
...到一个简单的Html.BeginForm,只是为了确定/排除此处AJAX有问题的可能性,也许是找不到UpdateTargetId。
另外,在Chrome上打开F12,切换到控制台标签,刷新页面并提交,以查看是否出现任何JavaScript错误。
最后,尝试暂时删除[FromBody]属性作为测试。 一些属性会影响路由,但我不确定此属性是否会成功,因为我从未使用过。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.