locked
Asp.Net MVC Dropdownlist Filter Table RRS feed

  • Question

  • User-47589850 posted

    Hi,

    I want to I filled users table on dropdownlist and select user filter table by user id. I can easily on webforms. But i cant on mvc. 

    I want first load page null table user select dropdownlist and data bind list. what should i use? Partialview,ajax ??

    how can I do it?

    Thanks

    Wednesday, July 8, 2020 4:39 PM

Answers

  • User1686398519 posted

    Hi asp.netlearning,

    • But partialview exception Object reference not set to an instance of an object.
      • For this error, it is because the object you are calling is empty. Based on the controller you gave, I guess you don't have an action to return a view with data.At the same time you have to modify your page code.

    Controller

            public PartialViewResult Listing()
            {
                int userid = 1;
                var orders = db.Orders.Include(s => s.Users).Where(x => x.user_id == userid);
                return PartialView(orders.ToList());
            }

    Page

    @{Html.RenderAction("Listing");}
    • However, the above suggestion is only to help you solve your error. If you want to achieve your needs, please refer to my revised code.
      • I combine ajax and partial view to display data.
      • For testing, I created the necessary model based on your code.

    Model

        public class Order
        {
            [Key]
            public int order_id { get; set; }
            public int user_id { get; set; }
            [ForeignKey("user_id")]
            public User Users { get; set; }
        }
        public class User
        {
            [Key]
            public int user_id { get; set; }
            public string name { get; set; }
            public string password { get; set; }
            public int Type { get; set; }
        }

    Controller

            public ActionResult Index()
            {
                var users = db.Users.Where(x => x.Type == 2).ToList();
                ViewBag.users = users;
                return View();
            }
            [HttpPost]
            public PartialViewResult Listing(int userid)
            {
                var orders = db.Orders.Include(s=>s.Users).Where(x => x.user_id == userid);
                return PartialView(orders.ToList());
            }

    Index

    @Html.DropDownList("dlusers", new SelectList(ViewBag.users, "user_id", "name"), "Select")
    <input id="Button1" type="button" value="button" />
    <div id="result"></div>
    @section scripts{
        <script>
            $("#Button1").click(function () {
                $.ajax({
                    "url": "@Url.Action("Listing")",
                    "type":"POST",
                    "data": { userid: $("#dlusers").val() },
                    "success": function (data) {
                        $("#result").html(data);
                    }
                });
            });
        </script>
    }

    Listing

        @model IEnumerable<WebApplication5.Models.Order>
        <table class="table">
            <tr>
                <td>order_id</td>
                <td>username</td>
            </tr>
            @foreach (var item in Model)
            {
                <tr>
                    <td>@Html.DisplayTextFor(m=>item.order_id)</td>
                    <td>@Html.DisplayTextFor(m => item.Users.name)</td>
                </tr>
            }
        </table>

    Here is the result.

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 9, 2020 10:55 AM

All replies

  • User475983607 posted

    asp.netlearning

    I want to I filled users table on dropdownlist and select user filter table by user id. I can easily on webforms. But i cant on mvc. 

    I want first load page null table user select dropdownlist and data bind list. what should i use? Partialview,ajax ??

    how can I do it?

    This site has a Getting Started with MVC and EF tutorial that covers filtering and more.  I recommend setting aside a few hours to go through the tutorial from start to finish.

    ASP.NET

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/

    ASP.NET Core

    https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/?view=aspnetcore-3.1

    Wednesday, July 8, 2020 4:45 PM
  • User-47589850 posted

    Hi,

    these sites simple crud function. I need like web form repeater listing examples like dropdownlist change event that for mvc. 

    Wednesday, July 8, 2020 4:58 PM
  • User475983607 posted

    these sites simple crud function. I need like web form repeater listing examples like dropdownlist change event that for mvc. 

    Clearly, you did not go through the tutorial.  The step Create a more complex data model for an ASP.NET MVC app sets up the table schema to handle a dropdown.  The next two steps get into how to build a View Model to handle HTML elements like a dropdown.   The step Update related data with EF in an ASP.NET MVC app illustrates how to implement the dropdown.

    If you have a list with dropdowns then your View Model will be a List<T> where each item in the list has the selected value for the dropdown.

    Wednesday, July 8, 2020 5:24 PM
  • User-474980206 posted

    MVC is quite a bit different from web forms. To help:

    1) assume viewstate disabled (only form fields included in post back data)
    2) no control tree. so no asp controls, assume just <% %>, <%= %> and <%: %>
    3) no support for auto postback. if you want this, just use javascript to do a form.submit() 
    4) as no asp controls, no post back event support. 

    while you can use the form collection, it more common to use model binding.

    learn razor syntax

      @Html.InputFor(m => m.Name)
      @Model.Description

    is same as

       <%= Html.InputFor(m => m.name) %>
       <%: Model.Description %>

    tag helpers are not controls, they are functions that return an html string. 

    if sound like you want to render a list on the change event of a select. you can do this with ajax and a partial, ajax and client render, or post back.

       @Html.DropdownFor(m => m.Users, Models.UsersList, new {onchange = "this.form.submit();"})

     

    Wednesday, July 8, 2020 6:08 PM
  • User-47589850 posted

    Hi,

    Thanks for information. I know a little about mvc. 

    this is what i want to do. But partialview exception Object reference not set to an instance of an object.

    <h5>Users Report</h5>
    @Html.BeginForm("Listing","Users",FormMethod.Post ){
    
    @Html.DropDownList("dlusers", new SelectList(ViewBag.users, "UserID", "Name"), "Select")
    <input id="Button1" type="button" value="button" />
    }
    @{Html.RenderPartial("Listing");}
    
     public ActionResult Index()
            {
                var users= db.Users.Where(x => x.Type== 2).ToList();
                ViewBag.users= users;
                return View();
            }
    
            [HttpPost]
            [ValidateAntiForgeryToken]
            public PartialViewResult Listing(FormCollection collection)
            {
                int userid= Convert.ToInt32(collection["dlusers"]);
                var orders= db.Orders.Include(s => s.Users).Where(x=>x.user_id==userid);
                return PartialView(orders.ToList());
            }
    
    

    Wednesday, July 8, 2020 7:58 PM
  • User475983607 posted

    I know a little about mvc. 

    this is what i want to do. But partialview exception Object reference not set to an instance of an object.

    Well, the Visual Studio debugger works the same in MVC and the error message generally displays the line of code that caused the error.  Not sure why you are hiding this information.  

    My best guess is the partial contains the dropdown and you forgot to populate the ViewBag.

    [HttpPost]
    [ValidateAntiForgeryToken]
    public PartialViewResult Listing(FormCollection collection)
    {
        int userid= Convert.ToInt32(collection["dlusers"]);
        
        var users= db.Users.Where(x => x.Type== userId).ToList();
        ViewBag.users= users;
        
        var orders= db.Orders.Include(s => s.Users).Where(x=>x.user_id==userid);
        return PartialView(orders.ToList());
    }

    Honesty, it is not clear why you are using a partial.  

    Is there some reason why you resist going through the MVC tutorial?  The tutorial has a lot of great tips and MVC programming patterns.  

    Anyway, if you want help with your current code base you'll need to share all the relevant code so the community is not forced to guess.

    Wednesday, July 8, 2020 8:26 PM
  • User-474980206 posted

    when your report view calls:

    @{Html.RenderPartial("Listing");
    

    because it does not pass a model or viewcontext, it uses the same as the report view. My guess is the Listing view is expecting a Model of type List<Orders> and it is null. But you don't show the view so we can only guess. 

    also the button is a button and will not do a form submit

    nowhere in the sample code is the action method Listing  used. also as it only has one parameter why use the form collection, it should be:

            [HttpPost]
            [ValidateAntiForgeryToken]
            public PartialViewResult Listing(int dlusers)
            {
                var orders= db.Orders.Include(s => s.Users).Where(x=>x.user_id == dlusers);
                return PartialView(orders.ToList());
            }

    Wednesday, July 8, 2020 10:00 PM
  • User1686398519 posted

    Hi asp.netlearning,

    • But partialview exception Object reference not set to an instance of an object.
      • For this error, it is because the object you are calling is empty. Based on the controller you gave, I guess you don't have an action to return a view with data.At the same time you have to modify your page code.

    Controller

            public PartialViewResult Listing()
            {
                int userid = 1;
                var orders = db.Orders.Include(s => s.Users).Where(x => x.user_id == userid);
                return PartialView(orders.ToList());
            }

    Page

    @{Html.RenderAction("Listing");}
    • However, the above suggestion is only to help you solve your error. If you want to achieve your needs, please refer to my revised code.
      • I combine ajax and partial view to display data.
      • For testing, I created the necessary model based on your code.

    Model

        public class Order
        {
            [Key]
            public int order_id { get; set; }
            public int user_id { get; set; }
            [ForeignKey("user_id")]
            public User Users { get; set; }
        }
        public class User
        {
            [Key]
            public int user_id { get; set; }
            public string name { get; set; }
            public string password { get; set; }
            public int Type { get; set; }
        }

    Controller

            public ActionResult Index()
            {
                var users = db.Users.Where(x => x.Type == 2).ToList();
                ViewBag.users = users;
                return View();
            }
            [HttpPost]
            public PartialViewResult Listing(int userid)
            {
                var orders = db.Orders.Include(s=>s.Users).Where(x => x.user_id == userid);
                return PartialView(orders.ToList());
            }

    Index

    @Html.DropDownList("dlusers", new SelectList(ViewBag.users, "user_id", "name"), "Select")
    <input id="Button1" type="button" value="button" />
    <div id="result"></div>
    @section scripts{
        <script>
            $("#Button1").click(function () {
                $.ajax({
                    "url": "@Url.Action("Listing")",
                    "type":"POST",
                    "data": { userid: $("#dlusers").val() },
                    "success": function (data) {
                        $("#result").html(data);
                    }
                });
            });
        </script>
    }

    Listing

        @model IEnumerable<WebApplication5.Models.Order>
        <table class="table">
            <tr>
                <td>order_id</td>
                <td>username</td>
            </tr>
            @foreach (var item in Model)
            {
                <tr>
                    <td>@Html.DisplayTextFor(m=>item.order_id)</td>
                    <td>@Html.DisplayTextFor(m => item.Users.name)</td>
                </tr>
            }
        </table>

    Here is the result.

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 9, 2020 10:55 AM