MVC:提交Ajax.Beginform后清除模型值

时间:2018-09-25 11:50:50

标签: asp.net-mvc binding model bootstrap-modal asp.net-ajax

我有这个模特:

public class VehiculeModalViewModel
{
    public VehiculeModalViewModel()
    {
        Title = "Nouveau véhicule";
        TextToDisplay = "Nom du nouveau véhicule :";
    }
    [Display(Name = "Nom")]
    [Required]
    [StringLength(10)]
    [Remote("IsVehiculeExists", "Defaults", HttpMethod = "POST", ErrorMessage = "Ce véhicule existe déjà.")]
    public string Name { get; set; }
    public string Title { get; set; }
    public string TextToDisplay { get; set; }
}

然后我将部分视图用作模式形式(这里只是绑定代码)

@model MultiRetouchesService.VehiculeModalViewModel
@Html.DisplayFor(m=>m.Title)
@Html.DisplayFor(m => m.TextToDisplay)
@Html.TextBoxFor(m => m.Name)

在主视图中,我正在使用Ajax.Begin表单助手来调用控制器方法并更新另一个局部视图。

@using (Ajax.BeginForm("CreateNewVehicule", "Defaults", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "vehiculesList", InsertionMode = InsertionMode.Replace },new { Id = "vehiculeForm" }))
{
    @Html.AntiForgeryToken()
    Html.RenderPartial("_ModalForm", Model.VehiculeModalViewModel);
}

这是控制器方法(基本上是创建车辆并更新其他局部视图):

[HttpPost]
[ValidateAntiForgeryToken]
public PartialViewResult CreateNewVehicule(VehiculeModalViewModel vehicule)
{
    if (ModelState.IsValid)
    {
        Vehicule newVehicule =  _vehiculeService.CreateNewVehicule(vehicule.Name);
    }
    IEnumerable<Vehicule> allVehicules = _vehiculeService.GetAllVehicules();
    return PartialView("_VehiculesList", allVehicules);
}

如果验证了模态(客户端和远程),则我将创建新的车辆,然后关闭模态表单。这就是我想要的。

但是,如果我重新打开模式,Textbox字段仍包含最后输入的name

如何避免这种情况?

在斯蒂芬评论之后,我添加了以下行:

$("#submitVehicule").click(function () {
    if ($('#vehiculeForm').valid()) {
        $('#closeVehicule').click();
        $('#vehiculeForm')[0].reset();
        var form = $('#vehiculeForm');
        form.data('validator', null);
        $.validator.unobtrusive.parse(form);
    }
})

0 个答案:

没有答案