ViewBag不保存状态

时间:2018-07-26 07:14:02

标签: c# .net model-view-controller

我测试了我的应用程序,而在测试时我发现了一个错误,我想这是来自ViewBage的错误。 我有500位医生和专科医师的名单,当我要编辑电话,地址等时,下拉列表显示给我SpeciltyName,这是列表中的第一名,因此它不保存医生的SpeciltyName 您可以检查下面的图片以更好地了解

enter image description here

enter image description here

ContactController.cs

// GET: Contacts/Edit/5
        public async Task<ActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Contact contact = await db.Contacts.FindAsync(id);
            if (contact == null)
            {
                return HttpNotFound();
            }

            ViewBag.TypeId = new SelectList(db.ContactTypes, "Id", "Name", contact.TypeId);
            ViewBag.CategoryId = new SelectList(db.ContactCategories.Where(s => s.Name != "Attorney" && s.Name != "Law Firm"), "Id", "Name", contact.CategoryId);
            ViewBag.ConCompanyId = new SelectList(db.Contacts.Where(s => s.ContactCategory.Name == "Insurance Carrier" || s.ContactCategory.Name == "Facility"), "Id", "Firstname");
            return View(contact);
        }

        // POST: Contacts/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit([Bind(Include = "Id,UserId,Title,Firstname,Lastname,isCompany,CategoryId,TypeId,DateOfBirth,Address1,Address2,City,State,Zip,Email,Mobile,Phone,Website,Country,LocationGPS,Gender,Notes,Latitude,Longitude")] Contact contact)
        {
            if (ModelState.IsValid)
            {

                db.Entry(contact).State = EntityState.Modified;
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }



            //ViewBag.Title = new SelectList(new[] { "Mr.", "Ms." }, contact.Title);
            ViewBag.TypeId = new SelectList(db.ContactTypes, "Id", "Name", contact.TypeId);
            ViewBag.CategoryId = new SelectList(db.ContactCategories.Where(s => s.Name != "Attorney" && s.Name != "Law Firm"), "Id", "Name", contact.CategoryId);
            ViewBag.ConCompanyId = new SelectList(db.Contacts.Where(s => s.ContactCategory.Name == "Insurance Carrier" || s.ContactCategory.Name == "Facility"), "Id", "Firstname");
            return View(contact);
        }

有人帮忙吗?

1 个答案:

答案 0 :(得分:4)

ViewBag值仅适用于当前请求。 viewbag代码确实被重定向到异步任务以设置ViewBag的值。因此,为ViewBag设置的值将随该请求一起消失。 解: 相反,如果您在相应的ActionResult中设置ViewBag的值而不是共享函数,则该ViewBag将保留并在视图中获取该值。

您可以改用TempData。 TempData在内部使用Session来存储值。 Please check this link