locked
I want to pass the selected value from controller to view RRS feed

  • Question

  • User417201021 posted

    I am very new to asp.net MVC and have my first project in hand.I am having 2 pages Home and Attendance. In Home controller, i am getting 3 client names C1, C2, C3 from database in my dropdownlistfor.

    @model WebApplication1.Models.ClientMdl  
        @{  
            ViewBag.Title = "Index";  
        }  
      
        <h2>ATOM</h2>  
    @using (Html.BeginForm("Index", "Home",FormMethod.Post,new { id="Frm1"}))  
    {  
        <table>  
            <tr></tr>  
            <tr>  
                <div>  
                    Select Client name<br />  
                    @Html.DropDownListFor(model => model.Client_Names, new SelectList(Model.Clients, "Client_Names", "Client_Names"), "Select Client", new { onchange = "document.getElementById('Frm1').submit();" })  
      
                    @*                @Html.TextBoxFor(model => model.Client_Names)*@  
                    @Html.ValidationMessageFor(model => model.Client_Names)  
                    <input type="submit" value="Submit" />  
      
                </div>  
            </tr>  
    </table>  
    }  

    I want user to select client name and click on submit. This saves the selected client name in a global variable which will be used across pages. Home Controller

    namespace WebApplication1.Controllers  
    {  
        public class HomeController : Controller  
        {  
            MdlCnStringContextClass _mdlCntxtcls = new MdlCnStringContextClass();  
            GlobalVaCls GVaCls = new GlobalVaCls();  
            GlblAttendanceCls glblAttendanceCls = new GlblAttendanceCls();  
            ClientMdl clntMdl = new ClientMdl();  
      
            /*        public ActionResult Index() 
                    { 
                        Client clntMdlObj = new Client(); 
                        clntMdlObj.Clients = GetAllClientNames(); 
                        return View(clntMdlObj); 
                    } 
     
     
     
                    private List<SelectListItem > GetAllClientNames() 
                    { 
                        List<SelectListItem> CNames = new List<SelectListItem>(); 
                        CNames = _mdlCntxtcls.clients.Select( c => new SelectListItem { Value=c.ClientID.ToString(),Text=c.Client_Names.ToString()}).ToList(); 
                        return (CNames); 
                    }*/  
      
            [HttpGet]  
            public ActionResult Index()  
            {  
                clntMdl.Clients = GetClientNames(clntMdl);  
                int InOutRws = glblAttendanceCls.Attendance();  
                if (GlobalVaCls.SelectedClient != null)  
                {  
                    ViewBag.VBg = GlobalVaCls.SelectedClient;  
                    ViewBag.InOtRwsCnt = InOutRws;  
      
                    if (InOutRws > 0)  
                    {  
                        var vClientNames = _mdlCntxtcls.Clients  
                            .Select(c => c.Client_Names);  
                              
      
                        return View(clntMdl);  
                    }  
                    else  
                    {  
                        return View(clntMdl);  
                    }  
                }  
                else  
                {  
                    return View(clntMdl);  
                }  
      
            }  
      
            [HttpPost ]  
            public ActionResult Index(ClientMdl client)  
            {  
                int InOutRws = glblAttendanceCls.Attendance();  
                ViewBag.InOtRwsCnt = InOutRws;  
                //Use this statement when getting the value of Dropdown text from View  
                string Client_Names = client.Client_Names.ToString();  
      
                //Gets the Client name from textbox in Index View  
                //string strClient = client.Client_Names;  
                //ViewBag.M = strClient;  
                GlobalVaCls.SelectedClient = client.Client_Names;  
                clntMdl.Clients = GetClientNames(clntMdl);  
                return View(clntMdl);  
            }  
    }  

    When i am on Attendance page and clicking Home link to browse to Home page. I want the client name which was saved in global variable to be the text of the dropdownlist in Home page.But i am facing an error as Object not set to an Instance in this statement

    @Html.DropDownListFor(model => model.Client_Names, new SelectList(Model.Clients, "Client_Names", "Client_Names"), "Select Client", new { onchange = "document.getElementById('Frm1').submit();" })   

    Here is where i need your help. Please revert if you need more clarifications.

    Monday, November 5, 2018 10:43 AM

Answers

  • User1520731567 posted

    Hi Jimmit_05,

    It seems that you want to store data between previous and next page.

    According to your error, it means the value is null,you could add breakpoints on your code to check if it is null.

    I think you could also use TempData to store temporary values.

    TempData can be used to store data between two consecutive requests. TempData values will be retained during redirection.

    For example:

    public ActionResult Index()
    {
        if (TempData["Category"] != null)
                {
            var Cat = (Category)TempData["Category"];
            var Products = from p in ctx.Products
                           where p.CategoryId == Cat.CategoryId
                           select p;
     
            TempData.Keep("Category");
     
            return View(Products.ToList());
        }
        else
        {
            return View(ctx.Products.ToList());
        }
    }

    More details,you could refer to:

    https://www.dotnetcurry.com/aspnet-mvc/1074/aspnet-mvc-pass-values-temp-data-session-request

    http://www.tutorialsteacher.com/mvc/tempdata-in-asp.net-mvc

    Best Regards.

    Yuki Tao

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, November 6, 2018 7:58 AM
  • User1520731567 posted

    Hi Jimmit_05,

    Here i have the value in a global variable when my Home page is loaded but i want that value to be already selected in my DropdownList.

    If you do not want to use TempData,you could also use Session.

    Or you can make a Class,pass data with model binding.

    For example:

    If you have 5 pages.

    You could make a Class,like:

            public class DataModel
            {
                public string One{ get; set; }
                public string Two{ get; set; }
                public string Three{ get; set; }
                public string Four{ get; set; }
                public string Five{ get; set; }
    ...
    some other fields... }

    When the user click button(type='submit'),it will pass the model to the next or previous action in controller,using this model to store data...

    Best Regards.

    Yuki Tao

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, November 27, 2018 9:55 AM

All replies

  • User1120430333 posted

    When i am on Attendance page and clicking Home link to browse to Home page. I want the client name which was saved in global variable to be the text of the dropdownlist in Home page.But i am facing an error as Object not set to an Instance in this statement

    @Html.DropDownListFor(model => model.Client_Names, new SelectList(Model.Clients, "Client_Names", "Client_Names"), "Select Client", new { onchange = "document.getElementById('Frm1').submit();" })

    Now of course when you click on something in a Web based solution, something like an object is lost becuase Web applications are stateless,  and the Web application knows nothing that was happening previously. It's blank slate,  and you have to get things built again even though they were there in another part of the program before you did a click.

    An object not set to an instance of a object means that code is referencing, trying to use an object, that is no longer in memory it's gone  a null valued object. It would be due to a Web application is stateless and nothing is kept in memory from one click to the next in simple laymen terminology.   

    You should be able to set a debug breakpoint on the line even in the View I believe and hover the objects on the line with the mousepoiter so that it will tell what object is a null valued object. 

    Monday, November 5, 2018 7:10 PM
  • User1520731567 posted

    Hi Jimmit_05,

    It seems that you want to store data between previous and next page.

    According to your error, it means the value is null,you could add breakpoints on your code to check if it is null.

    I think you could also use TempData to store temporary values.

    TempData can be used to store data between two consecutive requests. TempData values will be retained during redirection.

    For example:

    public ActionResult Index()
    {
        if (TempData["Category"] != null)
                {
            var Cat = (Category)TempData["Category"];
            var Products = from p in ctx.Products
                           where p.CategoryId == Cat.CategoryId
                           select p;
     
            TempData.Keep("Category");
     
            return View(Products.ToList());
        }
        else
        {
            return View(ctx.Products.ToList());
        }
    }

    More details,you could refer to:

    https://www.dotnetcurry.com/aspnet-mvc/1074/aspnet-mvc-pass-values-temp-data-session-request

    http://www.tutorialsteacher.com/mvc/tempdata-in-asp.net-mvc

    Best Regards.

    Yuki Tao

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, November 6, 2018 7:58 AM
  • User1315226703 posted

    You can simple using Tempdata,ViewData or ViewBag.

    Or You want to pass in model,so can insert selected value in Model and pass this model to View.

    Thursday, November 8, 2018 7:16 AM
  • User417201021 posted

    Hi,

    You are correct, great reply. this solved the error.

    Here, say i am selecting client C1 from the dropdownlist in Home and navigating to Attendance page. Now from Attendance when i am navigating back to Home, i want the client name C1 already selected on my dropdownlist.

    Please suggest, it would be great if you can show the code example.

    Thank you for your reply.

    Thursday, November 8, 2018 3:45 PM
  • User1520731567 posted

    Hi Jimmit_05,

    Here, say i am selecting client C1 from the dropdownlist in Home and navigating to Attendance page. Now from Attendance when i am navigating back to Home, i want the client name C1 already selected on my dropdownlist.

    Actually,you need to access TempData every redirecting the page.

    Determine the next behavior based on whether its value is empty or not.

    TempData is used to pass data from current request to subsequent request (i.e., redirecting from one page to another).

    Its life is too short and lies only till the target view is fully loaded. But you can persist data in TempData by calling the method Keep().

    You could refer to this link about How to Persist Data with TempData in MVC:

    https://www.codeproject.com/Tips/842080/How-to-Persist-Data-with-TempData-in-MVC

    Best Regards.

    Yuki Tao

    Monday, November 12, 2018 9:41 AM
  • User417201021 posted

    Here i have the value in a global variable when my Home page is loaded but i want that value to be already selected in my DropdownList.

    Thursday, November 22, 2018 2:27 PM
  • User1520731567 posted

    Hi Jimmit_05,

    Here i have the value in a global variable when my Home page is loaded but i want that value to be already selected in my DropdownList.

    If you do not want to use TempData,you could also use Session.

    Or you can make a Class,pass data with model binding.

    For example:

    If you have 5 pages.

    You could make a Class,like:

            public class DataModel
            {
                public string One{ get; set; }
                public string Two{ get; set; }
                public string Three{ get; set; }
                public string Four{ get; set; }
                public string Five{ get; set; }
    ...
    some other fields... }

    When the user click button(type='submit'),it will pass the model to the next or previous action in controller,using this model to store data...

    Best Regards.

    Yuki Tao

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, November 27, 2018 9:55 AM
  • User417201021 posted

    Hi Yuki.

    Really appreciate your efforts in resolving my query, but may be i am unable to explain my requiremnt.

    I will give you the real structure here

    1 I am on Home Page with dropdownlistfor with the vale "Select Client". Here i am selecting my client name "Client2"

    2 I am navigating to Attendance page by clicking the link in the Menu which opens Attendance page

    3 I am now clicking Home link in menu and opening Home Page

    4 Home page opens with dropdown's value as "Select Client".

    I want the client name already selected in the Pt. 1 as "Client2" and not "Select Client", as i donot want to keep reselecting the client name everytime i visit the Home page.

    It would be really helpful if you can also paste the code here.

    Thank you.

    Wednesday, November 28, 2018 3:45 PM
  • User475983607 posted

    Here i have the value in a global variable when my Home page is loaded but i want that value to be already selected in my DropdownList.

    If you are still relying on the following approach then it will either not work at all or produce unexpected results depending on how the classes are designed.

        public class HomeController : Controller  
        {  
            MdlCnStringContextClass _mdlCntxtcls = new MdlCnStringContextClass();  
            GlobalVaCls GVaCls = new GlobalVaCls();  
            GlblAttendanceCls glblAttendanceCls = new GlblAttendanceCls();  
            ClientMdl clntMdl = new ClientMdl();

    Controllers are created "new" on each and every request this includes the members.   Keep in mind that a web application is a single instance with many users which is very different from a desktop application where this approach would work.

    Please go through the Getting Started tutorials on this site to learn MVC patterns and practices.

    https://www.asp.net/learn

    The previous suggestions are exactly how to solve this "manage state" problem in MVC.

    Wednesday, November 28, 2018 3:58 PM
  • User417201021 posted

    Nicely explained. Thank you DA924

    Friday, November 30, 2018 4:22 PM