Ajax.BeginForm 将空值发送到控制器操作 ASP.NET MVC
Ajax.BeginForm sends null values to controller action ASP.NET MVC
我有一个部分视图,它包含 asp.net MVC 中的 ajax 表单,并且有一个包含两个不同模型的视图模型。
其中一个模型用于获取摘要信息,另一个用于向操作提交表单。
当我尝试从 ajax 表单提交数据以进行操作时,我遇到了空值。
这是我在 AccountController 中的操作代码
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<JsonResult> ChangePassword(ChangePasswordViewModel model)
{
var CurrentUser = GetCurrentUser();
if (ModelState.IsValid)
{
bool isOldPasswordTrue = await UserManager.CheckPasswordAsync(CurrentUser, model.CurrentPassword);
if (!isOldPasswordTrue)
{
return Json(new { result = "error", message = "رمز فعلی صحیح نمی باشد." }, JsonRequestBehavior.AllowGet);
}
var Result = await UserManager.ChangePasswordAsync(CurrentUser.Id, model.CurrentPassword, model.NewPassword);
if(Result != IdentityResult.Success)
{
return Json(new { result = "error", message = "خطا در تغییر رمز عبور." }, JsonRequestBehavior.AllowGet);
}
return Json(new { result = "success", message = "رمز عبور با موفقیت تغییر کرد. صفحه به صورت خودکار بارگذاری خواهد شد." }, JsonRequestBehavior.AllowGet);
}
return Json(model);
}
这是我的局部视图
@model iran_pcj.Models.UserInformationViewModel
<div class="myAccount-profile">
<div class="row align-items-center">
<div class="col-lg-4 col-md-5">
<div class="profile-image">
@if (Model.CurrentUser.ImagePath == null)
{
if (Model.CurrentUser.Gender == Gender.Male || Model.CurrentUser.Gender == Gender.Other)
{
<img src="~/Content/img/user_images/default_male.jpg" alt="image">
}
else
{
<img src="~/Content/img/user_images/default_female.jpg" alt="image">
}
}
else
{
<img src="~/Content/img/user_images/@Model.CurrentUser.ImagePath" alt="image">
}
</div>
</div>
<div class="col-lg-8 col-md-7">
<div class="profile-content">
<h3>@Model.CurrentUser.Firstname @Model.CurrentUser.LastName</h3>
<p>@Model.CurrentUser.Title</p>
<ul class="contact-info">
<li><i class='bx bx-envelope'></i> @Model.CurrentUser.Email</li>
<li><i class='bx bx-phone'></i> @Model.CurrentUser.PhoneNumber</li>
@if (Model.CurrentUser.Website != null)
{
<li><i class="bx bx-world"></i> <a href="@Model.CurrentUser.Website" target="_blank">@Model.CurrentUser.Website</a></li>
}
</ul>
<ul class="social">
@if (Model.CurrentUser.Facebook != null)
{
<li><a href="#" class="d-block" target="_blank"><i class='bx bxl-facebook'></i></a></li>
}
@if (Model.CurrentUser.Twitter != null)
{
<li><a href="#" class="d-block" target="_blank"><i class='bx bxl-twitter'></i></a></li>
}
@if (Model.CurrentUser.Instagram != null)
{
<li><a href="https://www.instagram.com/@Model.CurrentUser.Instagram" class="d-block" target="_blank"><i class='bx bxl-instagram'></i></a></li>
}
@if (Model.CurrentUser.Linkedin != null)
{
<li><a href="https://www.linkedin.com/in/@Model.CurrentUser.Linkedin" class="d-block" target="_blank"><i class='bx bxl-linkedin'></i></a></li>
}
</ul>
<a href="@Url.Action("ChangeAvatar", "Account")" class="btn btn-outline-primary"><i class="bx bx-image"></i> ویرایش تصویر</a>
<a href="#" class="btn btn-outline-success" id="ChangePassword"><i class="bx bx-lock-open"></i> تفییر رمز</a>
<a href="@Url.Action("Logout", "Account")" class="btn btn-outline-danger"><i class="bx bx-log-out"></i> خروج</a>
</div>
</div>
</div>
</div>
<div class="modal fade" id="AppModal" tabindex="-1" role="dialog" aria-labelledby="AppModallabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="AppModallabel"><i class="bx bx-lock-open"></i> تغییر رمز عبور</h5>
</div>
<div class="modal-body" id="modal-container">
<div id="changepass">
@using (Ajax.BeginForm("ChangePassword", "Account", new { CurrentPassword = Model.ChangePassword.CurrentPassword, NewPassword = Model.ChangePassword.NewPassword, NewPasswordConfirmation = Model.ChangePassword.NewPasswordConfirmation }, new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "ChangePasswordSuccess",
OnFailure = "ChangePasswordFailure"
}, new { @id = "changePassForm" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
@Html.LabelFor(model => model.ChangePassword.CurrentPassword, htmlAttributes: new { @class = "control-label col-md-12" })
<div class="col-md-12">
@Html.EditorFor(model => model.ChangePassword.CurrentPassword, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ChangePassword.CurrentPassword, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ChangePassword.NewPassword, htmlAttributes: new { @class = "control-label col-md-12" })
<div class="col-md-12">
@Html.EditorFor(model => model.ChangePassword.NewPassword, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ChangePassword.NewPassword, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ChangePassword.NewPasswordConfirmation, htmlAttributes: new { @class = "control-label col-md-12" })
<div class="col-md-12">
@Html.EditorFor(model => model.ChangePassword.NewPasswordConfirmation, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ChangePassword.NewPasswordConfirmation, "", new { @class = "text-danger" })
</div>
</div>
</div>
}
</div>
<div class="progress" style="height: 1px;visibility:hidden">
<div class="progress-bar" role="progressbar" style="width: 0%;" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="ChangPassSubmit" class="btn btn-outline-primary"><i class="bx bx-send"></i> ارسال</button>
<button type="button" class="btn btn-outline-danger" data-dismiss="modal" id="recoveryCancel"><i class="bx bx-x"></i> انصراف</button>
</div>
</div>
</div>
</div>
这是我的视图模型
UserInformationViewModel
public class UserInformationViewModel
{
public AppUser CurrentUser { get; set; }
public ChangePasswordViewModel ChangePassword { get; set; }
}
ChangePasswordViewModel
public class ChangePasswordViewModel
{
[Required(ErrorMessage = "{0} نمی تواند خالی باشد")]
[DataType(DataType.Password)]
[Display(Name = "کلمه عبور فعلی")]
public string CurrentPassword { get; set; }
[Required(ErrorMessage = "{0} نمی تواند خالی باشد")]
[DataType(DataType.Password)]
[Display(Name = "کلمه عبور جدید")]
public string NewPassword { get; set; }
[Required(ErrorMessage = "{0} نمی تواند خالی باشد")]
[DataType(DataType.Password)]
[Display(Name = "تکرار کلمه عبور")]
[System.ComponentModel.DataAnnotations.Compare("NewPassword", ErrorMessage = "رمز عبور با تکرارش همخوانی ندارد.")]
public string NewPasswordConfirmation { get; set; }
}
我的代码没有发现任何错误。可能是因为太累了,希望大家帮帮我。
发送
我发现了这个问题。
因为我使用包含两个视图模型的视图模型,所以我应该重命名我的输入。
在这种情况下,当我像这样使用上面的代码将数据发送到服务器时
__RequestVerificationToken: VLBnD4tC7ih5q9FAtVM9b-4-7lLbDSVhgeKh8Z-eJGfOoXOT96kiwd24SMAkzuRF70OH-5fr4NWeXl1hA6xKfO81llCUOTcIwZtP_bDbCutt4VM9RfPteMmRj9JlitMgLhxk3S_PmMH2YkfxOECRJA2
ChangePassword.CurrentPassword: 123456789
ChangePassword.NewPassword: 123456
ChangePassword.NewPasswordConfirmation: 123456
X-Requested-With: XMLHttpRequest
但是 ChangePassword
操作接受 CurrentPassword
、NewPassword
、NewPasswordConfirmation
所以我将 EditFor
更改为 PasswordFor
然后添加 Name
html 属性到我的代码如下:
@Html.PasswordFor(model => model.ChangePassword.CurrentPassword, new { @class = "form-control", Name = "CurrentPassword" })
其他字段同上。
希望这对大家有用
我有一个部分视图,它包含 asp.net MVC 中的 ajax 表单,并且有一个包含两个不同模型的视图模型。 其中一个模型用于获取摘要信息,另一个用于向操作提交表单。
当我尝试从 ajax 表单提交数据以进行操作时,我遇到了空值。
这是我在 AccountController 中的操作代码
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<JsonResult> ChangePassword(ChangePasswordViewModel model)
{
var CurrentUser = GetCurrentUser();
if (ModelState.IsValid)
{
bool isOldPasswordTrue = await UserManager.CheckPasswordAsync(CurrentUser, model.CurrentPassword);
if (!isOldPasswordTrue)
{
return Json(new { result = "error", message = "رمز فعلی صحیح نمی باشد." }, JsonRequestBehavior.AllowGet);
}
var Result = await UserManager.ChangePasswordAsync(CurrentUser.Id, model.CurrentPassword, model.NewPassword);
if(Result != IdentityResult.Success)
{
return Json(new { result = "error", message = "خطا در تغییر رمز عبور." }, JsonRequestBehavior.AllowGet);
}
return Json(new { result = "success", message = "رمز عبور با موفقیت تغییر کرد. صفحه به صورت خودکار بارگذاری خواهد شد." }, JsonRequestBehavior.AllowGet);
}
return Json(model);
}
这是我的局部视图
@model iran_pcj.Models.UserInformationViewModel
<div class="myAccount-profile">
<div class="row align-items-center">
<div class="col-lg-4 col-md-5">
<div class="profile-image">
@if (Model.CurrentUser.ImagePath == null)
{
if (Model.CurrentUser.Gender == Gender.Male || Model.CurrentUser.Gender == Gender.Other)
{
<img src="~/Content/img/user_images/default_male.jpg" alt="image">
}
else
{
<img src="~/Content/img/user_images/default_female.jpg" alt="image">
}
}
else
{
<img src="~/Content/img/user_images/@Model.CurrentUser.ImagePath" alt="image">
}
</div>
</div>
<div class="col-lg-8 col-md-7">
<div class="profile-content">
<h3>@Model.CurrentUser.Firstname @Model.CurrentUser.LastName</h3>
<p>@Model.CurrentUser.Title</p>
<ul class="contact-info">
<li><i class='bx bx-envelope'></i> @Model.CurrentUser.Email</li>
<li><i class='bx bx-phone'></i> @Model.CurrentUser.PhoneNumber</li>
@if (Model.CurrentUser.Website != null)
{
<li><i class="bx bx-world"></i> <a href="@Model.CurrentUser.Website" target="_blank">@Model.CurrentUser.Website</a></li>
}
</ul>
<ul class="social">
@if (Model.CurrentUser.Facebook != null)
{
<li><a href="#" class="d-block" target="_blank"><i class='bx bxl-facebook'></i></a></li>
}
@if (Model.CurrentUser.Twitter != null)
{
<li><a href="#" class="d-block" target="_blank"><i class='bx bxl-twitter'></i></a></li>
}
@if (Model.CurrentUser.Instagram != null)
{
<li><a href="https://www.instagram.com/@Model.CurrentUser.Instagram" class="d-block" target="_blank"><i class='bx bxl-instagram'></i></a></li>
}
@if (Model.CurrentUser.Linkedin != null)
{
<li><a href="https://www.linkedin.com/in/@Model.CurrentUser.Linkedin" class="d-block" target="_blank"><i class='bx bxl-linkedin'></i></a></li>
}
</ul>
<a href="@Url.Action("ChangeAvatar", "Account")" class="btn btn-outline-primary"><i class="bx bx-image"></i> ویرایش تصویر</a>
<a href="#" class="btn btn-outline-success" id="ChangePassword"><i class="bx bx-lock-open"></i> تفییر رمز</a>
<a href="@Url.Action("Logout", "Account")" class="btn btn-outline-danger"><i class="bx bx-log-out"></i> خروج</a>
</div>
</div>
</div>
</div>
<div class="modal fade" id="AppModal" tabindex="-1" role="dialog" aria-labelledby="AppModallabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="AppModallabel"><i class="bx bx-lock-open"></i> تغییر رمز عبور</h5>
</div>
<div class="modal-body" id="modal-container">
<div id="changepass">
@using (Ajax.BeginForm("ChangePassword", "Account", new { CurrentPassword = Model.ChangePassword.CurrentPassword, NewPassword = Model.ChangePassword.NewPassword, NewPasswordConfirmation = Model.ChangePassword.NewPasswordConfirmation }, new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "ChangePasswordSuccess",
OnFailure = "ChangePasswordFailure"
}, new { @id = "changePassForm" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
@Html.LabelFor(model => model.ChangePassword.CurrentPassword, htmlAttributes: new { @class = "control-label col-md-12" })
<div class="col-md-12">
@Html.EditorFor(model => model.ChangePassword.CurrentPassword, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ChangePassword.CurrentPassword, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ChangePassword.NewPassword, htmlAttributes: new { @class = "control-label col-md-12" })
<div class="col-md-12">
@Html.EditorFor(model => model.ChangePassword.NewPassword, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ChangePassword.NewPassword, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ChangePassword.NewPasswordConfirmation, htmlAttributes: new { @class = "control-label col-md-12" })
<div class="col-md-12">
@Html.EditorFor(model => model.ChangePassword.NewPasswordConfirmation, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ChangePassword.NewPasswordConfirmation, "", new { @class = "text-danger" })
</div>
</div>
</div>
}
</div>
<div class="progress" style="height: 1px;visibility:hidden">
<div class="progress-bar" role="progressbar" style="width: 0%;" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="ChangPassSubmit" class="btn btn-outline-primary"><i class="bx bx-send"></i> ارسال</button>
<button type="button" class="btn btn-outline-danger" data-dismiss="modal" id="recoveryCancel"><i class="bx bx-x"></i> انصراف</button>
</div>
</div>
</div>
</div>
这是我的视图模型
UserInformationViewModel
public class UserInformationViewModel
{
public AppUser CurrentUser { get; set; }
public ChangePasswordViewModel ChangePassword { get; set; }
}
ChangePasswordViewModel
public class ChangePasswordViewModel
{
[Required(ErrorMessage = "{0} نمی تواند خالی باشد")]
[DataType(DataType.Password)]
[Display(Name = "کلمه عبور فعلی")]
public string CurrentPassword { get; set; }
[Required(ErrorMessage = "{0} نمی تواند خالی باشد")]
[DataType(DataType.Password)]
[Display(Name = "کلمه عبور جدید")]
public string NewPassword { get; set; }
[Required(ErrorMessage = "{0} نمی تواند خالی باشد")]
[DataType(DataType.Password)]
[Display(Name = "تکرار کلمه عبور")]
[System.ComponentModel.DataAnnotations.Compare("NewPassword", ErrorMessage = "رمز عبور با تکرارش همخوانی ندارد.")]
public string NewPasswordConfirmation { get; set; }
}
我的代码没有发现任何错误。可能是因为太累了,希望大家帮帮我。 发送
我发现了这个问题。
因为我使用包含两个视图模型的视图模型,所以我应该重命名我的输入。
在这种情况下,当我像这样使用上面的代码将数据发送到服务器时
__RequestVerificationToken: VLBnD4tC7ih5q9FAtVM9b-4-7lLbDSVhgeKh8Z-eJGfOoXOT96kiwd24SMAkzuRF70OH-5fr4NWeXl1hA6xKfO81llCUOTcIwZtP_bDbCutt4VM9RfPteMmRj9JlitMgLhxk3S_PmMH2YkfxOECRJA2
ChangePassword.CurrentPassword: 123456789
ChangePassword.NewPassword: 123456
ChangePassword.NewPasswordConfirmation: 123456
X-Requested-With: XMLHttpRequest
但是 ChangePassword
操作接受 CurrentPassword
、NewPassword
、NewPasswordConfirmation
所以我将 EditFor
更改为 PasswordFor
然后添加 Name
html 属性到我的代码如下:
@Html.PasswordFor(model => model.ChangePassword.CurrentPassword, new { @class = "form-control", Name = "CurrentPassword" })
其他字段同上。
希望这对大家有用