Shanks Limbu
Shanks Limbu

Reputation: 147

populate dropdownlist in View

Hy, I've a json file with list of countries in my contentroot. It looks like this

{
  "countries": [
    {
      "name": "Afghanistan",
      "cca2": "af",
      "code": 93
    },
    {
      "name": "Albania",
      "cca2": "al",
      "code": 355
    },
    {
      "name": "Algeria",
      "cca2": "dz",
      "code": 213
    }
 ]
}

I want to populate that list of countires to my dropdownlist which is in my Views as [email protected] from my controller but I get null exceptions. System.NullReferenceException: 'Object reference not set to an instance of an object.'

I tried to deserilize my json file in model class like this

public class AccountController : Controller
    {
     //Other stuffs
     private readonly IWebHostEnvironment _env;
     public AccountController(IWebHostEnvironment env)
     {
       _env = env
     }
     public void OnGet(Registration registration)
        {
            registration.CountryDropDownList = GetCountryItems();
        }
        public List<SelectListItem> GetCountryItems()
        {
            string filepath = Path.Combine(_env.ContentRootPath, "CountryList.json");
            string jsonlist = System.IO.File.ReadAllText(filepath);
            var result = JsonConvert.DeserializeObject<RootCountry>(jsonlist);
            List<SelectListItem> _countrydropdownlist = new List<SelectListItem>();
            foreach (var nation in result.Countries)
            {
                _countrydropdownlist.Add(new SelectListItem { Value = nation.Code.ToString(), Text = nation.Name });
            }
            return _countrydropdownlist;
        }

I believe my void OnGet is not being hit. Update- My full view code.

@model TravelMate.ModelFolder.RegistrationModel.Registration

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, shrink-to-fit=no" />
    @{
        ViewBag.Title = "Registration";
    }

    <link href="~/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col text-center">
                <br />
                <img src="~/Image/GeneralUser.jpg" width="200" height="400" />
                <br />
                <h3>User Registration</h3>
            </div>
            <form method="post">
                <br />
                <h3>Person Details</h3>
                <div asp-validation-summary="All" class="text-danger"></div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label asp-for="Name"></label>
                            <input asp-for="Name" class="form-control" />
                            <span asp-validation-for="Name" class="text-danger"></span>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label asp-for="DateOfBirth"></label>
                            <input asp-for="DateOfBirth" class="form-control" />
                            <span asp-validation-for="DateOfBirth" class="text-danger"></span>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label asp-for="Mobile"></label>
                            <input asp-for="Mobile" class="form-control" />
                            <span asp-validation-for="Mobile" class="text-danger"></span>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label asp-for="Email"></label>
                            <input asp-for="Email" class="form-control" />
                            <span asp-validation-for="Email" class="text-danger"></span>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label asp-for="Country"></label>
                            <select asp-for="Country" asp-items="@Model.CountryDropDownList">
                                <option selected disabled> ---Select Country---</option>
                            </select>
                            <span asp-validation-for="Country" class="text-danger"></span>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label asp-for="Gender"></label>
                            <select asp-for="Gender" class="form-control">
                                <option value="0" selected disabled>Select Gender</option>
                                <option value="1">Male</option>
                                <option value="2">Female</option>
                            </select>
                            <span asp-validation-for="Gender" class="text-danger"></span>
                        </div>
                    </div>
                </div>
                <br />
                <h3>Sign-in Details</h3>
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label asp-for="UserName">User Name</label>
                            <input asp-for="UserName" class="form-control" />
                            <span asp-validation-for="UserName" class="text-danger"></span>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label asp-for="Password"></label>
                            <input asp-for="Password" class="form-control" />
                            <span asp-validation-for="Password" class="text-danger"></span>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label asp-for="ConfirmPassword"></label>
                            <input asp-for="ConfirmPassword" class="form-control" />
                            <span asp-validation-for="ConfirmPassword" class="text-danger"></span>
                        </div>
                    </div>
                </div>
                <button type="submit" class="btn btn-primary">Register</button>
            </form>
        </div>
    </div>
    <script src="~/jquery/jquery.slim.min.js"></script>
    <script src="~/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

My error- Null Exception Error

Error in quickwatch.

Upvotes: 0

Views: 125

Answers (1)

Fei Han
Fei Han

Reputation: 27793

I want to populate that list of countires to my dropdownlist

To achieve your requirement, you can refer to the following code snippet.

RegistrationModel class

public class RegistrationModel : PageModel
{
    private IWebHostEnvironment _env;
    public string Country { get; set; }
    public List<SelectListItem> Countrydropdownlist { get; set; }
    public RegistrationModel(IWebHostEnvironment env)
    {
        _env = env;
    }

    public void OnGet()
    {
        Countrydropdownlist = GetCountryItems();
    }

    public List<SelectListItem> GetCountryItems()
    {
        var filepath = Path.Combine(_env.ContentRootPath, "countrylist.json");
        var jsonlist = System.IO.File.ReadAllText(filepath);

        var result = JsonConvert.DeserializeObject<RootCountry>(jsonlist);
        List<SelectListItem> _countrydropdownlist = new List<SelectListItem>();
        foreach (var nation in result.Countries)
        {
            _countrydropdownlist.Add(new SelectListItem { Value = nation.Code.ToString(), Text = nation.Name });
        }

        return _countrydropdownlist;
    }
}

In Registration.cshtml

<select asp-for="Country" asp-items="Model.Countrydropdownlist"></select> 

The countrylist.json file is stored as below

enter image description here

Test Result

enter image description here

Note: for more information about Content root and Web root, please check following doc

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/?view=aspnetcore-3.1&tabs=windows#content-root

Update:

Based on your new update, it seems that you'd like to populate and display dropdown in MVC project, to achieve it, please refer to following example.

public class AccountController : Controller
{
    private readonly IWebHostEnvironment _env;
    public AccountController(IWebHostEnvironment env)
    {
        _env = env;
    }

    public IActionResult Index()
    {
        ViewBag.Countrydropdownlist = GetCountryItems();

        return View();
    }

    //...

In Index.cshtml file under Views/Account folder

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>

<select name="Country" asp-items="ViewBag.Countrydropdownlist"></select> 

Besides, you can know more about view discovery and how to pass data to views from this doc:

https://learn.microsoft.com/en-us/aspnet/core/mvc/views/overview?view=aspnetcore-3.1#passing-data-to-views

Update2:

It seems that you pass items and populate <select> using viewmodel data, please make sure you provided and passed data to view from your controller action, like below.

//...
//your code logic here

var model = new Registration
{
    CountryDropDownList = GetCountryItems()
};

return View(model);

Upvotes: 0

Related Questions