0

What i trying to do is to fill list with names with data from model and set to View and show in view With dropDownListFor ...is my logic a right ...and what i should do else

Model :

public class Categories{
public int id {get;set}
public string categoryName{get;set}
    public List<CategoryName> catNames {get;set;} //or IEnumerable<>
}

controller:

public ActionResult getSomething(){
public List<CategoryName>   list = new List<CategoryName>() ;
public List<CategoryName> names= list.FindAll(x=>x.categoryName);
return View(names)
}

1 Answer 1

1

You have invalid C# syntax but you are on the right track.

Define a model:

public class CategoriesModel
{
    public int Id { get; set }
    public string CategoryName { get; set }
    public List<CategoryName> CategoryNames { get; set; }
}

a controller:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new CategoriesModel();
        model.CategoryNames = GetCategoryNames();
        return View(model);
    }

    private List<CategoryName> GetCategoryNames()
    {
        // TODO: you could obviously fetch your categories from your DAL
        // instead of hardcoding them as shown in this example
        var categories = new List<CategoryName>();
        categories.Add(new CategoryName { Id = 1, Name = "category 1" });
        categories.Add(new CategoryName { Id = 2, Name = "category 2" });
        categories.Add(new CategoryName { Id = 3, Name = "category 3" });
        return categories;
    }
}

and finally a strongly typed view to the model:

@model CategoriesModel
@using (Html.BeginForm())
{
    @Html.DropDownListFor(
        x => x.CategoryName, 
        new SelectList(Model.CategoryName, "Id", "Name")
    )
    <button type="submit"> OK</button>
}

You haven't shown your CategoryName model but in this example I am supposing that it has properties called Id and Name which is what the DropDownList is bound to.

Sign up to request clarification or add additional context in comments.

1 Comment

@user2026573,StackOverflow is an English speaking website, so please write in English. If you want to fill the categories from your database you could simply query it instead of hardcoding the values as shown in my answer. For example if you are using Entity Framework and already have a DbContext you could directly fetch the category names from it: model.CategoryNames = db.CategoryNames.ToList();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.