简体   繁体   中英

ASP.NET MVC: How to pass parameter between controllers before and after post

I have below controllers:

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

My main problem is that user is allowed to select model.MaterialPaymentRequestId from drop-down and he/she may leave it with no value selected. MaterialPaymentRequestId is used in first controller (befor post) to find Parent title from db and pass it to view using ViewBag, however if user does not select MaterialPaymentRequestId dropdown items, after postback, I lost MaterialPaymentRequestId . Currently I read Request variable and look inside url to find parameters to lookup for parentID. My url calls are like http://localhost:46813/Admin/MaterialPaymentRequestSbuItem/CreateChild?parentId=23 .

However this practice seems like a bad practice than I cannot pass v variable between two controller methods a process like this:

Controller method(get) ---> View ---> Controller method(post)

Currently I feel a bit stuck in MVC!

i hope i got your point right, you can use an @Html.hiddenfor(model => model.ParentId) in your view it will store ParentId value from query string and when user submits form will be posted to POST method so you dont need to look into url to get it. use a viewmodel with ParentId property and do as below

public class MaterialPaymentsViewModel {
    //other properties
    public int ParentId {get;set;}
}

public ActionResult CreateChild(int? parentId)
{
    var model = new MaterialPaymentsViewModel{ParentId = parentId};
    //other stuff

    return View(model);
}

//View

@using (Html.beginform()){
//
@html.hiddenfor(m => m.ParentId)
//submit
}


[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateChild(MaterialPaymentsViewModel  model)
{
    if(model.ParentId != null)
{
 //
}
  //
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM