Umbraco Surface Controller or RenderMvcController - asp.net-mvc

Hi I have my 'home' controller and a 'sort' controller in umbraco 7. The 'home' controller works fine for the index action as it is overridden from RenderMvcController. Firstly I am confused which controller I should using in which instance i.e a surface controller or a rendermvccontroller. I cant seem to access the twitter action below which is something I need for ajax. Do I need to put the twitter action in a surface controller or could I use a regular mvc controller in umbraco?
public override ActionResult Index(RenderModel model)
{
var storedProcedure = new StoredProcedure()
{
ConnectionString = ConfigurationManager.ConnectionStrings["CentralDbContext"].ConnectionString
};
DataSet ds = storedProcedure.ExecuteProcedureToDataSet("GetHomePage");
IMapSetup map = new MapHomePage();
HomePage homepage = map.Setup<HomePage>(ds);
homepage.Slideshow = CurrentPage.AncestorsOrSelf(1).First().Descendants("SlideshowItem").Take(5).AsMany<Slideshow>();
this._weatherSettings.DefaultLocation = "warrington";
homepage.Forecast = new Forecaster(this._weatherSettings, this._cacheHelper).GetWeather(this._weatherSettings.DefaultLocation);
return CurrentTemplate(homepage);
}
public ActionResult TwitterSort(int? page)
{
int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
var storedProcedure = new StoredProcedure()
{
ConnectionString = ConfigurationManager.ConnectionStrings["CentralDbContext"].ConnectionString
};
DataSet ds = storedProcedure.ExecuteProcedureToDataSet("GetHomePage");
IMapSetup map = new MapHomePage();
HomePage homepage = map.Setup<HomePage>(ds);
if (Request.IsAjaxRequest())
{
return PartialView("umbTweets", homepage.Twitter.ToPagedList(currentPageIndex, DefaultPageSize));
}
return PartialView(homepage.Twitter.ToPagedList(currentPageIndex, DefaultPageSize));
}

My Approach is:
Render controller is only for displaying data to user.
Surface controller is for interaction (I use this for interaction mainly ajax, or forms)
For rendering child action you can use following example:
http://our.umbraco.org/documentation/Reference/Mvc/child-actions
Update:
To implement custom routing you can have a look on
http://cpodesign.com/blog/umbraco-implementing-routing-in-mvc/

Related

Call controller without "clicking" in asp.net MVC

Is there a way to call a controller without clicking on a link?
By this I mean, without using #Html.ActionLink for example, something automatic that's call after a condition.
Thanks in advance !
Edit :
There is some code :
if (IsPost)
{
if (!Request["idInterventions"].IsEmpty())
{
string[] AllStrings = Request["idInterventions"].Split(',');
List<int> list = new List<int>();
foreach (string item in AllStrings)
{
int value = int.Parse(item);
list.Add(value);
}
Model.toFacture(list);
isDone = true;
//Need to call a controller method here
}
}
So my code is triggered after a POST.
In Razor, you can use
Html.RenderAction("ActionName", "ControllerName", new { Area = "SomeArea", someParameter = Model.SomeParameterValue });
This renders the view returned by the action directly.
In controllers, you can use
return RedirectToAction("ActionName", "ControllerName");
This will result in a HTTP 302 Found redirect.

How to capture the values in a gridview dynamically in asp.net DevExpress MVC

as I can make this code dynamically
public ActionResult EditingUpdate()
{
//...
string fName = GridViewExtension.GetEditValue<string>("FirstName");
string lName = GridViewExtension.GetEditValue<string>("LastName");
//...
}
There are several ways of doing this, it depends on how you want to present the action to the user. I would recommend you follow the example on the DevExpress Demo Page. They show you how to pass the model into your controller.
Controller:
public ActionResult EditingUpdate(MyObject model)
{
string fName = model.FirstName;
....
....
{
Now, the following step is where you have few choices. You can call the controller method in several different ways, all from the gridview partial view. Again, refer to the DevExpress Demo Page. If you want to call the method from an edit action (which is what I assume based on your method name), then you use:
settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "MyController", Action = "EditingUpdate" };
But there are other ways of calling this method, such as
settings.CustomActionRouteValues = new { Controller = "MyController", Action = "EditingUpdate" };
It all depends when you want the gridview to call this method.
Follow the example in the demo, that will help you decide how you want it. Good luck!

Scan for all actions in the site

How do I create action links for all actions in the site?
I want to put those action links into a menu system.
I was hoping I can do something like
foreach controller in controllers {
foreach action in controller{
stringbuilder.writeline(
"<li>"+actionlink(menu, action, controller)+"<li>"
);
}
}
Here's my take on it:
var controllers = Assembly.GetCallingAssembly().GetTypes().Where(type => type.IsSubclassOf(typeof(Controller))).ToList();
var controlList = controllers.Select(controller =>
new
{
Actions = GetActions(controller),
Name = controller.Name,
}).ToList();
The method GetActions as follows:
public static List<String> GetActions(Type controller)
{
// List of links
var items = new List<String>();
// Get a descriptor of this controller
var controllerDesc = new ReflectedControllerDescriptor(controller);
// Look at each action in the controller
foreach (var action in controllerDesc.GetCanonicalActions())
{
// Get any attributes (filters) on the action
var attributes = action.GetCustomAttributes(false);
// Look at each attribute
var validAction =
attributes.All(filter => !(filter is HttpPostAttribute) && !(filter is ChildActionOnlyAttribute));
// Add the action to the list if it's "valid"
if (validAction)
items.Add(action.ActionName);
}
return items;
}
If you need a menu system checkout the MVC Sitemap Provider, it will give you absolute control on what to render depending on the roles you've defined on your membership implementation.
Here is approach how get all actions from controller Asp.net Mvc: List all the actions on a controller with specific attribute or Accessing the list of Controllers/Actions in an ASP.NET MVC application
For achieving your goal you should find all controllers in your project with Assembly.GetExportedTypes() and filter only sub classes of ControllerBase and for each controller call new ReflectedControllerDescriptor(typeof(TController)).GetCanonicalActions() from 2nd link.

How can I have an object which can be accessed from different controllers?

I'm working with ASP.Net MVC4, I customize my login, this is ok, I would like save this object USER and I can access from differents controllers and differents Areas. I was trying to defined this object as "static" but I can't acces to values of object:
if (Servicio.ValidarUsuario())
{
string Mensaje = "";
Models.AdmUsuario oAdmUsuario = new Models.AdmUsuario();
oAdmUsuario.Au_codusuario = login.UserName;
Servicio.RetornaEntidad<Models.AdmUsuario>(ref Mensaje, "admsis.adm_usuario", oAdmUsuario.getPk(), oAdmUsuario);
***Models.AdmUsuario.UserWeb = oAdmUsuario;***
FormsAuthentication.SetAuthCookie(login.UserName, false);
Session["Modulo"] = null;
Session["Menu"] = null;
return RedirectToAction("index", "raMainReclamo", new { area = "Reclamos" });
}
In the model I define:
public static AdmUsuario UserWeb;
But I can't access to value.
Do you have any idea, how I can to access the values ​​of an object from different controllers in different areas?
You need a way to store the object between requests. You could put the object in Session Memory and pull it back out.
{
// Other Code
Session["AdmUsuario"] = oAdmUsuario;
return RedirectToAction("index", "raMainReclamo", new { area = "Reclamos" });
}
Controller in Reclamos Area
public class raMainReclamoController : Controller
{
public ActionResult Index() {
var oAdmUsuario = Session["AdmUsuario"] as Models.AdmUsuario;
// Other Code
}
}
However, the a more standard approach would be to persist the object to a database and then pull it back out. You could read up on using Entity Framework to access a sql database. I like to use RavenDB for storage as it makes saving objects really easy.
** UPDATE IN RESPONSE TO COMMENTS **
This is just psuedo code as I don't know what you are using to connect to postgres.
{
// Other Code
oAdmUsuario = postgresContext.Store(oAdmUsuario);
postgresContext.SaveChanges();
return RedirectToAction("index", "raMainReclamo", new { area = "Reclamos", id = oAdmnUsuario.Id });
}
Controller in Reclamos Area
public class raMainReclamoController : Controller
{
public ActionResult Index(int id) {
var oAdmUsuario = postgresContext.GetById<Models.AdmUsuario>(id);
// Other Code
}

NullReferenceException while storing data to session in an ASP.NET MVC 3 Controller

I have a following View Method in an ASP.NET MVC 3 Controller that retrieves data from Amazon SimpleDb, stores it in a list and then stores that list object in a session. But at the line where I am storing the userBox object in a session (Session["userBox"] = userBox), I am getting a NullReferenceException. I am sure that userBox is not null. Even if I try to store a simple string in a session (like Session["userBox"] = "test") I still get NullReferenceException.
Here is the code:
public ActionResult SetSidebarAccountBoxSessions(string id)
{
string selectExpression = "select * from MySimpleDBDomain where itemName()='" + id + "'";
SelectRequest sreq = new SelectRequest().WithSelectExpression(selectExpression);
SelectResponse sres = sdb.Select(sreq);
List<User> userBox = new List<User>();
if (sres.IsSetSelectResult())
{
SelectResult selectresult = sres.SelectResult;
foreach (Item item in selectresult.Item)
{
string a = item.Name;
userBox.Add(new User
{
imageThug = item.Attribute[0].Value,
name = item.Attribute[3].Value,
bio = item.Attribute[1].Value
});
}
}
Session["userBox"] = userBox;
return View();
}
I am calling this SetSideBarAccountBoxSessions(id) method from another controller method:
HomeController hc = new HomeController();
hc.SetSidebarAccountBoxSessions(item.Name);
Can this be the problem? Please help.
I think this problem is related to the fact that you create HomeController by yourself. You can try to use TransferToRouteResult to transfer the action to HomeController.
You an find the code of TransferToRouteResult in this link:
How to simulate Server.Transfer in ASP.NET MVC?

Resources