2

I want to get list of users in my MVC.

Visual Studio keeps saying that I'm

"Use of unassigned local variable 'model' ".

I've tried different methods but can't fix the error. Can anyone tell me where I'm doing wrong?.

 public ActionResult Search(string searchTerm)       
 {
        var users = new DirectorySource<UserModel>(ROOT,SearchScope.Subtree);

        IEnumerable<UserModel> model;

        var res = from usr in users
                  where usr.DisplayName.StartsWith(searchTerm)                     
                  select usr.DisplayName;

        foreach (var result in res)
        {
            model.OrderBy(p => p.DisplayName).ToList();
        }

        if (Request.IsAjaxRequest())
        {
            return PartialView("_search", model);
        }

        return View(model);
 }
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Kasra
  • 59
  • 6

3 Answers3

3

You are only declaring your model, but not instantiating it. You should instantiate it before trying to call methods on it (like OrderBy). Secondly, you should not perform the OrderBy inside a for loop, it's enough to do it only once. You might want to instantiate the model with the result of the Linq query and select usr at the end, not the display names.

var model = (from usr in users
            where usr.DisplayName.StartsWith(searchTerm)                     
            select usr).OrderBy(u => u.DisplayName).ToList();
Octavian Mărculescu
  • 4,312
  • 1
  • 16
  • 29
2

Error is very clear, you have to provide default value before usage.

IEnumerable<UserModel> model = new List<UserModel>();

or

IEnumerable<UserModel> model = null;

That is to take away your error, but you can simplify your code with below statement.

IEnumerable<UserModel> model =  users.Where(usr=>usr.DisplayName.StartsWith(searchTerm))
                                      .OrderBy(usr=>usr.DisplayName).ToList();
Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
0

Instead of:

IEnumerable<UserModel> model;

try this:

List<UserModel> model = new List<UserModel>();

or:

IEnumerable<UserModel> model = new List<UserModel>();
diiN__________
  • 7,393
  • 6
  • 42
  • 69