无效的modelState之后,ASP MVC清除model.var1值

时间:2019-03-11 06:38:40

标签: c# asp.net-mvc post modelstate

发布表单后,如果有任何错误(model.IsValid == false),我想清除1个变量值
但这不起作用

    [HttpPost]
    [AllowAnonymous]
    public async Task<ActionResult> Register(]VMRegister model)
    { 
        if (model.Captcha == string.Empty || model.Captcha.Trim().ToLower() != Session["CAPTCHA"].ToString())
        {
            ModelState.AddModelError("Captcha", "Invalid captcha entered.");
        }

        if (ModelState.IsValid)
        {

            //Insert to DB
            return RedirectToAction("Index", "Home");

        }

        /********************************
        If model state is invalid, it populates old values in form
        I want to clear captcha value, as new captcha will be appeared
        model.Captcha = string.Empty; is not working
        *********************************/
        model.Captcha = string.Empty;            
        return View(model);
    }

1 个答案:

答案 0 :(得分:0)

同时写出

ModelState.Remove("Captcha");
model.Captcha = string.Empty;

希望这会起作用