【发布时间】:2016-05-30 19:42:12
【问题描述】:
我有以下控制器:
// GET: /MaterialPaymentRequestSbuItem/CreateChild
public ActionResult CreateChild(int? parentId)
{
if (parentId==null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var parenetRequest = (from request in db.MaterialPaymentRequests
where request.Id==(int)parentId
select request);
ViewBag.MaterialPaymentRequestId = new SelectList(parenetRequest, "Id", "Description", (int)parentId);
ViewBag.ParentID = parentId;
if (parenetRequest!=null && parenetRequest.First()!=null)
ViewBag.ParentTitle = parenetRequest.First().Description;
return View();
}
// POST: /MaterialPaymentRequestSbuItem/Create
// 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 ActionResult CreateChild([Bind(Include = "Id,Name,Unit,UnitPrice,MaterialPaymentRequestId,Quantity")] MaterialPaymentRequestSubItem materialpaymentrequestsubitem)
{
if (ModelState.IsValid)
{
try
{
db.MaterialPaymentRequestSubItems.Add(materialpaymentrequestsubitem);
db.SaveChanges();
}
catch (Exception e)
{
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
}
updateTotalPriceOfParentPaymentRequest(db, db.MaterialPaymentRequests.Find(materialpaymentrequestsubitem.MaterialPaymentRequestId));
return RedirectToAction("List", new { id = materialpaymentrequestsubitem.MaterialPaymentRequestId });
}
ViewBag.MaterialPaymentRequestId = new SelectList(db.PaymentRequests, "Id", "Description", materialpaymentrequestsubitem.MaterialPaymentRequestId);
//need to becheked
ViewBag.ParentID = materialpaymentrequestsubitem.MaterialPaymentRequestId;
if (Request != null && Request["parentID"] != null)
{
try
{
int id = Int32.Parse(Request["parentID"]);
ViewBag.ParentTitle = db.MaterialPaymentRequests.Find(id).Description;
}
catch(Exception e)
{
}
}
return View(materialpaymentrequestsubitem);
}
我的主要问题是允许用户从下拉列表中选择 model.MaterialPaymentRequestId 并且他/她可能没有选择任何值。 MaterialPaymentRequestId 用于第一个控制器(在发布之前)从 db 中查找父标题并使用 ViewBag 将其传递给查看,但是如果用户没有选择 MaterialPaymentRequestId 下拉项目,在回发后,我丢失了 MaterialPaymentRequestId。目前,我阅读了Request 变量并在 url 内部查找参数以查找 parentID。
我的 url 调用类似于 http://localhost:46813/Admin/MaterialPaymentRequestSbuItem/CreateChild?parentId=23。
但是这种做法似乎是一种不好的做法,因为我不能在两个控制器方法之间传递 v 变量,如下所示:
控制器方法(get) ---> 查看 ---> 控制器方法(post)
目前我感觉有点卡在 MVC 中!
【问题讨论】:
-
您是否尝试过使用 TempData 而不是 ViewBag 查看此链接以获取详细信息msdn.microsoft.com/en-us/library/…
标签: c# asp.net-mvc razor asp.net-mvc-5