InfinityGoesAround
InfinityGoesAround

Reputation: 1021

How to check if controller names are not the same in mvc?

I am using paging. the ideer is now that if you leave the controller paging will be cleared. I am usinng a session for paging. But now if you leave the controller and go back to the previous controller the page is still selected what you selected before.

So the ideer is now to build a generic method in a helper class that checks if the controller names are not the same. then clear session. and set the paging to 1.

I have this:

public static object GetSelectedModelId(this HtmlHelper helper,string ControllerName)
{
    string currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"];

    if ((ControllerName != null) && (currentControllerName.Equals(ControllerName, StringComparison.CurrentCultureIgnoreCase))) {
                HttpContext.Current.Session[currentControllerName] = ControllerName;
    }
    else {
       HttpContext.Current.Session.Clear();
       return true;
    }

    return false;
}

public static void SetSelectedModelId(string ControllerName, object ModelId) {
}

But how to check now if the controller names are not the same?

Thank you

I changed to this:

public static object GetSelectedModelId(string ControllerName)
{
    var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"];
    string currentControllerName = (string)controller;

    if ((ControllerName != null) && (currentControllerName.Equals(ControllerName, StringComparison.CurrentCultureIgnoreCase))) {
                    return controller;
    }
    else {
    }
}

public static void SetSelectedModelId(string ControllerName, object ModelId)
{
    var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"];
    string currentControllerName = (string)controller;

    if ((ControllerName != null) && (currentControllerName.Equals(ControllerName, StringComparison.CurrentCultureIgnoreCase))) {
                    HttpContext.Current.Session[currentControllerName] = ControllerName;
    }
    else {
        HttpContext.Current.Session.Clear();               
    }
}

and this for example are my two Edit methods of ProductController:

[HttpGet]
public ActionResult Edit(int? id)
{
    //TempData["editedId"] = id;           
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    Product product = db.Products.Find(id);

    if (product == null)
    {
        throw new HttpException((int) HttpStatusCode.NotFound, null);
    }

    SetCreateEditProductLists(product, customerSchema);

    EditProductModel editModel = new EditProductModel();          
    editModel.Product = product;
    editModel.Db = db;           

    DeserializeAuthenticationSettings(editModel);
    DeserializePaymentSettings(editModel);
    DeserializeConnectors(editModel);
    DeserializePrefillMappings(editModel);
    //Session["IdProduct"] = id;
    ModelHelper.GetSelectedModelId("Product");

    ViewBag.Model = editModel;

    return View(editModel);
}

// POST: /Product/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]
[ValidateInput(false)]
public ActionResult Edit(EditProductModel entry)
{
    entry.Product.ModificationDate = DateTime.UtcNow;            

    if (ModelState.IsValid)
    {
        db.Entry(entry.Product).State = EntityState.Modified;

        db.Entry(entry.Product).Property(model => model.Guid).IsModified = false;
        db.Entry(entry.Product).Property(model => model.CreationDate).IsModified = false;
        db.Entry(entry.Product).Property(model => model.IsProduction).IsModified = false;

        entry.Product.IsProduction = StateHelper.IsTestMode() ? false : true;

        HandleProductSelections(entry.Product);
        SerializeAuthenticationSettings(entry);
        SerializePaymentSettings(entry);
        SerializeConnectors(entry);
        SerializePrefillMappings(entry);

        if (SaveDbChanges()) {
            // Record an audit trail event for an updated product.
            {
                ATEvent atEvent = AuditTrailHelper.NewEvent(ATEventType.ProductUpdated, HttpContext, db.Schema, entry.Product);
                atEvent.StringArg = entry.Product.Name;
                ATEventLogger.Current.LogEvent(atEvent);
            }
                    AddDelayedNotification(Resources.Entity.Environment.ItemSavedMessage, Notification.NotificationType.Success);

            var page = Session["pageProduct"];                  
            //Session["IdProduct"] = entry.Product.Id;
            ModelHelper.GetSelectedModelId("Product");

            return RedirectToAction("Index", new { page, id = entry.Product.Id });
        }
    }
            AddDelayedNotification(Resources.Entity.Environment.ItemNotSavedError, Notification.NotificationType.Error);
            return Edit(entry.Product.Id);
        }

I try this:

public static object GetSelectedModelId(string ControllerName)
{
    var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"];
    string currentControllerName = (string)HttpContext.Current.Session[ControllerName];

    if ((controller != null) && (currentControllerName.Equals(ControllerName, StringComparison.CurrentCultureIgnoreCase))) {
            return controller;               
    }
    else {
        HttpContext.Current.Session.Clear();
    }

    return controller;
}

But then I get this error:

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 49: string currentControllerName = (string)HttpContext.Current.Session[ControllerName];
Line 50:
Line 51: if ((controller != null) && (currentControllerName.Equals(ControllerName, StringComparison.CurrentCultureIgnoreCase))) {
Line 52: return controller;
Line 53: }

If I do this:

public static object GetSelectedModelId(string ControllerName)
{
    var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"];
    string currentControllerName = (string)HttpContext.Current.Session[ControllerName];

    if ((controller != null) && (currentControllerName != null)  &&  (currentControllerName.Equals(ControllerName, StringComparison.CurrentCultureIgnoreCase))) {
                return controller;               
    }
    else {
        HttpContext.Current.Session.Clear();
    }

    return controller;
}

I still dont get the previous controller name

Upvotes: 0

Views: 628

Answers (2)

InfinityGoesAround
InfinityGoesAround

Reputation: 1021

I solved like this:

 public static object GetSelectedModelId(string ControllerName)
        {
            //var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;
            string controller = (string)HttpContext.Current.Session["controller"];
            object mid = null;


            if (controller != null && controller.Equals(ControllerName, StringComparison.OrdinalIgnoreCase)) 
             mid =   HttpContext.Current.Session["SelectedModelId"];            
            HttpContext.Current.Session.Remove("SelectedModelId");
            HttpContext.Current.Session.Remove("controller");

            return mid;
        }

        public static void SetSelectedModelId(string ControllerName, object ModelId)
        {
            HttpContext.Current.Session["controller"] = ControllerName;
            HttpContext.Current.Session["SelectedModelId"] = ModelId;
        }

Upvotes: 1

Abdul Khan
Abdul Khan

Reputation: 363

Try Using :

var controller = Request.UrlReferrer.Segments
.Skip(1).Take(1).SingleOrDefault() ?? "Home").Trim('/'); 
// Home is default controller

var action = (Request.UrlReferrer.Segments
.Skip(2).Take(1).SingleOrDefault() ?? "Index").Trim('/'); 
// Index is default action  

This Should let you extract the Controller name and you should try using TempData for subsequent request to store the previous controller.As HTTP is stateless.

Upvotes: 0

Related Questions