验证后丢失表单值



使用ViewModel进行验证:

public class CCvm
{
    [Required(ErrorMessage = "Please enter your Name")]
    public string cardHolderName { get; set; }
}

我的控制器在帖子中调用任务:

public async Task<ActionResult> Pay(FormCollection form, CCvm model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }
}

观点:

@model GCwholesale.Models.CCvm
@{
    Layout = "~/Views/Shared/_HomeSubPageLayout.cshtml";
    ViewBag.Title = "Secure Checkout";
}
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
      <div class="Payment">
         <label>Name on Card: </label>
         @Html.EditorFor(model => model.cardHolderName, new { htmlAttributes = new { @placeholder = "Cardholder Name Please", @Value = ViewBag.Name } })<br />
         @Html.ValidationMessageFor(model => model.cardHolderName)
       <button class="submitCheckout">SUBMIT NOW</button>
      </div>
}

但当验证失败时,表单中的数据就会消失。

谢谢你看。

您不需要在EditorFor中设置@Value = ViewBag.Name

@Html.EditorFor(model => model.cardHolderName, 
new { htmlAttributes = new { @placeholder = "Cardholder Name Please" } })

此外,您不需要FormCollection作为参数,因为您已经有了CCvm模型

public async Task<ActionResult> Pay(CCvm model){
{
   //...
}
@Value = ViewBag.Name

您没有设置ViewBag.Name,因此它不会有值,并且会导致输入为空。去掉它,让HtmlHelper根据发布的模型中的值来设置它。

相关内容

  • 没有找到相关文章

最新更新