gpt4 book ai didi

c# - ViewBag 不保存状态

转载 作者:太空宇宙 更新时间:2023-11-03 20:54:53 28 4
gpt4 key购买 nike

我测试了我的应用程序,在测试时我发现了一个错误,我认为它来自 ViewBage。我有 500 名医生和专科医生的名单,当我想编辑电话、地址等时,下拉菜单会显示列表中第一个专科医生的名字,所以它不会保存医生的专科医生名字您可以查看下面的图片以便更好地理解

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);
}

有什么帮助吗?

最佳答案

ViewBag 值仅适用于当前请求。 viewbag 代码确实被重定向到异步任务以设置 ViewBag 的值。因此,为 ViewBag 设置的值将随着该请求一起消失。解决方案:相反,如果您在相应的 ActionResult 中设置 ViewBag 的值而不是共享函数,那么它将继续存在并且您将在 View 中获得值。

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

关于c# - ViewBag 不保存状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51533025/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com