验证错误后的RedirectToAction [英] RedirectToAction after validation errors

查看:42
本文介绍了验证错误后的RedirectToAction的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我具有通常的Edit操作,则GET可以通过ID的方式检索对象并将其显示在编辑表单中.POST的下一个操作是获取ViewModel中的值并更新数据库中的对象.

If I have the usual Edit actions, one for GET to retrieve an object by it's ID and to display it in an edit form. The next for POST to take the values in the ViewModel and update the object in the database.

public virtual ActionResult Edit(int id)

[HttpPost]
public ActionResult Edit(VehicleVariantEditSaveViewModel viewModel)

如果在POST操作中的模型绑定期间发生错误,我知道我可以将RedirectToAction返回到GET操作,并通过将其复制到TempData并在GET操作中进行重定向后检索它来保留ModelState验证错误.

If an error occurs during model binding in the POST action, I understand I can RedirectToAction back to the GET action and preserve the ModelState validation errors by copying it to TempData and retrieving it after the redirect in the GET action.

if (TempData["ViewData"] != null)
{
    ViewData = (ViewDataDictionary)TempData["ViewData"];
}

然后如何将包含先前无效ModelState的ViewData转换为新模型以发送到视图,以便用户看到带有验证警告的无效输入?奇怪的是,如果我将从数据库中检索到的ViewModel的新实例(包含原始有效数据)传递给View(),则会忽略该错误,并显示ViewData中的(无效)数据!

How do I then convert that ViewData, which includes the previous invalid ModelState, into a new model to send to the view so the user sees their invalid input with validation warnings? Oddly enough if I pass in a new instance of my ViewModel retrieved from the database (with the original valid data) to the View() this is ignored and the (invalid) data in the ViewData is displayed!

谢谢

推荐答案

我遇到了类似的问题,因此决定使用以下模式:

I had a similar problem and decided to use the following pattern:

public ActionResult PersonalRecord(Guid id)
{
    if (TempData["Model"] == null)
    {
        var personalRecord = _context.PersonalRecords.Single(p => p.UserId == id);
        var model = personalRecord.ToPersonalRecordModel();
        return View(model);
    }
    else
    {
        ViewData = (ViewDataDictionary) TempData["ViewData"];
        return View(TempData["Model"]);
    }
}

[HttpPost]
public ActionResult PersonalRecord(PersonalRecordModel model)
{
    try
    {
        if (ModelState.IsValid)
        {
            var personalRecord = _context.PersonalRecords.Single(u => u.UserId == model.UserId);
            personalRecord.Email = model.Email;
            personalRecord.DOB = model.DOB;
            personalRecord.PrimaryPhone = model.PrimaryPhone;
            _context.Update(personalRecord);
            _context.SaveChanges();
            return RedirectToAction("PersonalRecord");
        }
    }
    catch (DbEntityValidationException ex)
    {
        var errors = ex.EntityValidationErrors.First();
        foreach (var propertyError in errors.ValidationErrors)
        {
            ModelState.AddModelError(propertyError.PropertyName, propertyError.ErrorMessage);
        }
    }

    TempData["Model"] = model;
    TempData["ViewData"] = ViewData;

    return RedirectToAction("PersonalRecord", new { id = model.UserId });
}

希望这会有所帮助.

这篇关于验证错误后的RedirectToAction的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆