Hawks1998
Hawks1998

Reputation: 73

MVC ViewModel and Sql queries

I am new to MVC, coming from a classic ASP shop. We are used to writing our own SQL selects to pull information into our asp pages. I am trying to find similar ways to do this in MVC and I found an example at asp.net mvc and sql queries that I am trying to follow.

I think I understand most of it but I am hung up on the following: //convert the data into a string[] and return it..

Can anyone expand on this for me or give me other examples?

What I am trying to accomplish is to pull data from a table and create a treeview in my view.

class MainPageViewModel
{
    //this data is from a different table.
    //and goes on the left of the page
    public string Categories {get; set;}
    //this data is also from a different table.
    //and goes on the center of the page
    public List<Products> Products {get; set;}
}

Controller:

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        MainPageViewModel vm = new MainPageViewModel();
        vm.Categories = GetCategories();
        //use the GetProducts() to get your products and add them.
        vm.Products.Add(...); 
        return View(vm); //pass it into the page
    }

    string[] GetCategories()
    {
        DataTable data = GetDataFromQuery("SELECT * FROM Categories WHERE..");
        //convert the data into a string[] and return it..
    }
    //maybe it has to return something else instead of string[]? 
    string[] GetProducts()
    {
        DataTable data = GetDataFromQuery("SELECT * FROM Products WHERE..");
        //convert the data into a string[] and return it..
    }

    DataTable GetDataFromQuery(string query)
    {
        SqlDataAdapter adap = 
         new SqlDataAdapter(query, "<your connection string>");
        DataTable data = new DataTable();
        adap.Fill(data);
        return data;
    }  
}

Upvotes: 2

Views: 1118

Answers (1)

Osman Bulut
Osman Bulut

Reputation: 21

You don't have write sql code.You can make it easily with Linq to Sql. Just add solution the linq to sql classes.Then you will add database and you can connect with database without sql code.

Upvotes: 1

Related Questions