多次发布后从Viewbag/tempdata中丢失数据 [英] Losing data from viewbag/tempdata after multiple post

查看:70
本文介绍了多次发布后从Viewbag/tempdata中丢失数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在传递价值时遇到问题.我是MVC的初学者,我读过有关 ViewBag TempData 的信息,我知道它不起作用,但我不知道如何使它起作用.我的问题:

I've got problem with passing value. I am beginner in MVC, I read about ViewBag, TempData and I know it shouldn't work but I don't know how to make it work otherway. My problem:

有2种型号:动物 Visit

在我的AnimalView中,我得到了所有动物的清单,并且得到了这个ActionLink:

in my AnimalView I got list of all animals and I got this ActionLink:

@Html.ActionLink("Add Visit", "Create", "Visit", new { id = item.AnimalID }, null) 

它转到带有ID传递的Create GET方法,我得到一个视图来创建访问,我可以提交它,一切都很好,但是..

it goes to Create GET method with id passed, I get a view to create visit I can submit it and everything is fine but..

例如,如果我没有设置访问时间,则模型不会更新,并且当方法返回到 Create Visit 视图时,我没有AnimalID 已经...可以在发布失败时some1告诉我如何保持该值吗?

for example if I don't set time for visit, model will not update and when method goes back to Create Visit View I don't have AnimalID already... can some1 tell me how to keep this value when post fails?

公共ActionResult创建(int id){动物动物= db.Animals.Find(id);如果(动物==空){返回HttpNotFound();}

public ActionResult Create(int id) { Animal animal = db.Animals.Find(id); if (animal == null) { return HttpNotFound(); }

       TempData["AnimalID"] = id;
        return View();

    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "VisitID,AnimalID,DoctorID,VisitDate,VisitHour,Price,Recognition,Medicines,VisitDescription")] Visit visit)
    {



        if (ModelState.IsValid)
        {
            visit.DoctorID = (int)Session["Doctors"];

            db.Visits.Add(visit);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(visit);
    }

推荐答案

ViewBag和TempData仅保留一个请求的信息.如果modelstate无效,则必须重新设置ViewBag和TempData值.

ViewBag and TempData only retain their information for one request. If the modelstate is not valid, you must re-set the ViewBag and TempData values.

这篇关于多次发布后从Viewbag/tempdata中丢失数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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