.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

asp.net MVC ViewData

Posted By:      Posted Date: October 26, 2010    Points: 0   Category :ASP.Net
ViewData["Title"] is accessible only the current view? or it is possible to access other views also?

View Complete Post

More Related Resource Links

DropDownList problems : The ViewData item that has the key 'userTYPE_id_user_type' is of type 'Sy

Hello,I've been searching for that problem for hours...I have two table :          -user          -userTypeI'm trying to create a user, wich as a column id_userType, so I'm trying to do a dropdownlist with the userType List I've that error code : The ViewData item that has the key 'userTYPE_id_user_type' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'. // // GET: /User/Create public ActionResult Create() { //Send to the view, the userTypeList IEnumerable<SelectListItem> userTypeList = new SelectList(_userRepository.FindAllUserType().Distinct().ToList(), "id_user_type", "Description"); ViewData["userType_id_user_type"] = userTypeList; return View(); } here the post controller // // POST: /User/Create [HttpPost] public ActionResult Create(users user) { if (ModelState.IsValid) { try { _userRepository.addUser(user); _userRepository.save(); return RedirectToAction("Index"); } catch { return Vie

Viewdata lost in handleerror

Anybody know why my viewdata is lost when HandleError filter kicks in? Below is the question posted on SO by somebody else but the solution looks overly complicated , is there a better way? http://stackoverflow.com/questions/1794936/how-do-i-pass-viewdata-to-a-handleerror-view

There is no ViewData item of type 'IEnumerable' that has the key 'Carrera'.

When running the HttpGet action, it works fine. But when I run the HttpPost action, I recieve the error in the title. Can anyone help me out? Is it because the HttpPost doesn't have a ViewData declared? Thanks for the help.[HttpGet] public ActionResult Crear() { CarreraRepository carreraRepository = new CarreraRepository(); var carreras = carreraRepository.FindAll().OrderBy(x => x.Nombre); var carrerasList = new SelectList(carreras, "ID", "Nombre"); ViewData["Carreras"] = carrerasList; Materia materia = new Materia(); return View(materia); } [HttpPost] public ActionResult Crear(Materia materia, FormCollection values) { if (ModelState.IsValid) { repo.Add(materia); repo.Save(); return RedirectToAction("Index"); } return View(materia); }

MVC 3 - EditorFor - Not rendering additional viewData

Hay Have seen in the MusicStore PDF witch can be sownloaded from wwww.asp.net,That is it possible to render additional vew data.so:I have my ViewDataModelpublic class PageViewData : Cms.Web.Areas.Management.Model.ViewData.BaseViewData { public ICollection<Page> PageList { get; set; } public Page CurrentPage { get; set; } public ICollection<PageTemplate> PageTemplateList { get; set; } public ICollection<Language> LanguageList { get; set; } public PageViewData(IPrincipal user, MessageCollection messageCollection) : base(user, messageCollection) {} }I have the Model: public class Page : BasePage { public virtual string Keyword { get; set; } [Required] public virtual Language Language { get; set; } public virtual PageTemplate Template { get; set; } public virtual bool IsFrontPage { get; set; } public Page() { } } In my controller, I add the data into the model: public ActionResult New() { this.CmsViewData.CurrentPage = new Page(); this.CmsViewData.PageTemplateList = this.PageTemplateService.GetList(); this.CmsViewData.LanguageList = this.LanguageService.GetList(); return View("New", this.CmsViewData); } And I try to render it with H

TempData and ViewData issue MVC


I'm building a user registration wizard with ASP.NET.  I'm redirecting the user to a different view for each step of the wizard. Initially, I was using TempData to store values but I realized that a couple of my values will need to persist beyond one request.  

So now I'm trying to use ViewData but the behavior is different.  When using TempData, I am able to render the view with the data but when I use ViewData, I get "Object reference not set to an instance of an object" when it attempts to render the view.

When I use TempData, it works, but only for the next request (by design from my understanding).

Here is my code.  Any ideas on what I'm doing wrong?  Also, if anyone has suggestions on to better handle a user registration wizard, I'm all ears.  Thanks.

ICompanyInterface service = new CompanyRepository();

bool compWebsite = service.CheckWebsite(model.Website);

if (compWebsite == true)


    ViewData["CompanyInfo"] = service.GetCompanyInfo(model.Website);


ViewData / Passing data


I have the following code.  When the View is rendered, I get "Object reference not set to an instance of an object" on the ViewData["Role"].  Not sure what I'm doing wrong...


        public int CheckUserRoles(string Username)
            int groupCheck = 1;

                using (DirectoryEntry de = new DirectoryEntry())
                    using (DirectorySearcher adSearch = new DirectorySearcher(de))
                        StringBuilder groupsList = new StringBuilder();
                        adSearch.Filter = "(sAMAccountName=" + Username + ")";
                        SearchResult result = adSearch.FindOne();

                        if (result != null)
                            foreach (string item in result.Properties["memberOf"])
                                var query = from role in db.Roles
                                            where role.Name == item
                                            select role;

                                if (query.Count() > 0)

Partial View Updating Parent VIew ViewData?


From MSDN:

"When a partial view is instantiated, it gets its own copy of the ViewDataDictionary object that is available to the parent view. The partial view therefore has access to the data of the parent view. However, if the partial view updates the data, those updates affect only the partial view's ViewData object. The parent view's data is not changed.


Is there a common way around this?

For instance I have a View containing two Partial Views (User Controls) that source the same data from the Parents ViewData. The first Partial View is able to update (add/delete) certain data from the Parents View Data, however the second Partial View sources the same data but obviously isn't reflecting the changes owing to the above MSDN statement.


Using ViewData.ModelMetadata.Properties in Controller


Is it possible to change Properties of ViewData.ModelMetadata in Controller?. For example, can I do the following to change the display information of the LogOnModel:

       // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
            ViewData.Model = new LogOnModel();
            foreach (var prop in ViewData.ModelMetadata.Properties)
                if (prop.PropertyName == "UserName")
                    prop.DisplayName = "Nombre de Usuario";
                if (prop.PropertyName == "Password")
                    prop.DisplayName = "Contraseña";
                if (prop.PropertyName == "RememberMe")
                    prop.DisplayName = "Recordarme?";

            return View();

When I do that there is no errors but DisplayName is not change. I'm trying to localize strings to different languages and also to make some attributes of the model different depending on users roles. I've been investigating many ways of doing i

Custom Controls ViewData


I have the following scenario,

2 custom web control with following details;

  1. Control1 has 2 buttons, button1, button2
  2. Control2 has 3 drop down boxes

Control1 is added to page by registering the control statically using

<%@ Register Assembly="control1" Namespace="control1"

    TagPrefix="cc2" %>


Control1 is available when the page is loaded, when button1 in control1 is clicked, I am dynamically generating the control2 and adding it in a static collection inside OnInit

Event. Static collection is required to preserve the controls on postback. The static collection is then loaded into PlaceHolder control.

When button2 on the control is clicked, I am dynamically generating control1 and adding it to the placeholder as mentioned above.


The drop down values in the custom control added statically on the page by registering the controls preserves the data on post back. The dynamically added controls do not preserve the data on postback.

Any pointers, samples in this regard will be helpful.


ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend