1st question is: Is this how you do a database model since placing it in views/controllers is not correct.
There are tutorials out there but they use "Entity Framework" is this better or is this standard way to use or can I do it my way?
This is in the "Models" folder in DatabaseModels.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MySql.Data.MySqlClient;
using System.Collections;
namespace News.Models
{
public class DatabaseModels
{
MySqlConnection con;
public ArrayList getTitles(){
con = new MySqlConnection("Server=127.0.0.1;Uid=root;Pwd=password;Database=newsdata");
con.Open();
ArrayList alNews = new ArrayList();
MySqlCommand queryTitles = new MySqlCommand("SELECT * FROM newsdata",con );
MySqlDataReader dr = queryTitles.ExecuteReader();
while (dr.Read())
{
alNews.Add(dr["Title"]);
}
con.Close();
return alNews;
}
}
}
So if the above is correct should return an ArrayList.
So I did this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MySql.Data.MySqlClient;
using News.Models;
namespace News.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
DatabaseModels dm = new DatabaseModels();
ViewBag.Titles = dm.getTitles();
return View();
}
public ActionResult About()
{
ViewBag.AboutUs = "Team of developers";
return View();
}
public ActionResult Forum()
{
return View();
}
}
}
meanwhile at index.cshtml
@using System.Collections;
@{
ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
<p>
To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>
<table>
@{
ArrayList al = new ArrayList();
al = @ViewBag.Titles;
foreach(string newsTitle in al){
<tr>
<td>
@newsTitle
</td>
</tr>
}
}
</table>
So is this the "correct" way of doing things assuming i'm not using entity framework?
I've search around and a lot(all) of the tutorials uses entity frame work, so it is difficult to see what are the other standards like creating database connections, retrieving of data and displaying of data using the MVC(3) way without EF.
I learnt asp.net webforms/websites so the above method is somewhat similar to having a class file with database connections and any form of manipulating data methods.
This post has been edited by aklo: 25 February 2012 - 04:11 AM

New Topic/Question
Reply



MultiQuote




|