Problemas com MVC3. Meu projeto não funciona.

02/03/2012

0

Deveria vir uma lista de informações do banco e quando eu starto a aplicação, nada é listado. Esse exemplo eu peguei de um livro da Novatec e não gostei do livro. Não explica muito e os exemplos não funcionam. O Autor deu um exemplo na URL e na imagem do livro a URL dele é diferente. Abaixo os códigos. Ele pede que a URL seja essa: localhost/AppCapitulo4/Categorie. Com essa dá um erro vindo do IIS e isso não entendi. Se deixo com a URL padrão que sobe junto com o F5 do Visual Studio, aí a página Index sobe, mas sem os dados do banco. Mas os nomes do campo vem, porem vazios. Abaixo os código do projeto.
O Model

namespace AppCapitulo4.Models
{
    public class CategoriesRepository
    {
        public List<Categorie> GetAllCategories() {
            ConnectionStringSettings getString = WebConfigurationManager.ConnectionStrings[nwind] as ConnectionStringSettings;
            if (getString != null) {
                string sSql = select CategoryID,CategoryName, Description from Categories;
                using (SqlConnection conn = new SqlConnection(getString.ConnectionString)) {
                    List<Categorie> lst = new List<Categorie>();                    
                    
                    SqlDataReader dr = null;
                    conn.Open();
                    SqlCommand cmd = new SqlCommand(sSql, conn);                    
                   
                    dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    if (dr.HasRows) {
                        int categoryID   = dr.GetOrdinal(CategoryID);
                        int categoryName = dr.GetOrdinal(CategoryName);
                        int description  = dr.GetOrdinal(Description);                        

                        while (dr.Read()) {
                            Categorie p = new Categorie();
                            p.CategoryID = dr.GetInt32(categoryID);
                            p.CategoryName = dr.GetString(categoryName);
                            p.Description = dr.GetString(description).ToString();
                        }
                    }
                    return lst;
                }
            }
            return null;
        }
        public class Categorie {
            public int CategoryID { get; set; }
            public string CategoryName { get; set; }
            public string Description { get; set; }
        }
    }
}


O View


<asp:Content ID=Content1 ContentPlaceHolderID=TitleContent runat=server>
    Index
</asp:Content>

<asp:Content ID=Content2 ContentPlaceHolderID=MainContent runat=server>

<h2>Index</h2>
<p>
    <%: Html.ActionLink(Create New, Create) %>
</p>
<table>
    <tr>
        <th></th>
        <th>
            CategoryID
        </th>
        <th>
            CategoryName
        </th>
        <th>
            Description
        </th>
    </tr>

<% foreach (var item in Model) { %>
    <tr>
        <td>
            <%: Html.ActionLink(Edit, Edit, new {  id=item.CategoryID  }) %> |
            <%: Html.ActionLink(Details, Details, new { id = item.CategoryID })%> |
            <%: Html.ActionLink(Delete, Delete, new { id = item.CategoryID })%>
        </td>
        <td>
            <%: item.CategoryID %>
        </td>
        <td>
            <%: item.CategoryName %>
        </td>
        <td>
            <%: item.Description %>
        </td>
    </tr>  
<% } %>
</table>
</asp:Content>


O Controller


namespace AppCapitulo4.Controllers
{
    public class CategorieController : Controller
    {
        CategoriesRepository _db = new CategoriesRepository();

        public ActionResult Index()
        {
            var model = _db.GetAllCategories();
            if (model == null)
                return View(NotFound);
            else
                return View(model);
        }

    }
}


O Global.asax


 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute(.axd/{*pathInfo});

            routes.MapRoute(
                Default, // Route name
                //, // URL with parameters
                new { controller = Categorie, action = Index, id = UrlParameter.Optional } // Parameter defaults
            );        }


É mais ou menos isso.
Pjava

Pjava

Responder

Posts

05/03/2012

Rodrigo Odasaki

Pessoal da Devmedia precisa arrumar este problema do código nos posts.
Está impossível de ajudar.
Responder

05/03/2012

Thiago Garcez

Posta como texto mesmo, para pode ler..
Responder

06/03/2012

Pjava

O Model

namespace AppCapitulo4.Models
{
public class CategoriesRepository
{
public List<Categorie> GetAllCategories() {
ConnectionStringSettings getString = WebConfigurationManager.ConnectionStrings[nwind] as ConnectionStringSettings;
if (getString != null) {
string sSql = select CategoryID,CategoryName, Description from Categories;
using (SqlConnection conn = new SqlConnection(getString.ConnectionString)) {
List<Categorie> lst = new List<Categorie>();

SqlDataReader dr = null;
conn.Open();
SqlCommand cmd = new SqlCommand(sSql, conn);

dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows) {
int categoryID = dr.GetOrdinal(CategoryID);
int categoryName = dr.GetOrdinal(CategoryName);
int description = dr.GetOrdinal(Description);

while (dr.Read()) {
Categorie p = new Categorie();
p.CategoryID = dr.GetInt32(categoryID);
p.CategoryName = dr.GetString(categoryName);
p.Description = dr.GetString(description).ToString();
}
}
return lst;
}
}
return null;
}
public class Categorie {
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public string Description { get; set; }
}
}
}

O View

<%@ Page Title= Language=C# MasterPageFile=~/Views/Shared/Site.Master Inherits=System.Web.Mvc.ViewPage<IEnumerable<AppCapitulo4.Models.CategoriesRepository+Categorie>> %>

<asp:Content ID=Content1 ContentPlaceHolderID=TitleContent runat=server>
Index
</asp:Content>

<asp:Content ID=Content2 ContentPlaceHolderID=MainContent runat=server>

<h2>Index</h2>

<p>
<%: Html.ActionLink(Create New, Create) %>
</p>
<table>
<tr>
<th></th>
<th>
CategoryID
</th>
<th>
CategoryName
</th>
<th>
Description
</th>
</tr>

<% foreach (var item in Model) { %>
<tr>
<td>
<%: Html.ActionLink(Edit, Edit, new { id=item.CategoryID }) %> |
<%: Html.ActionLink(Details, Details, new { id = item.CategoryID })%> |
<%: Html.ActionLink(Delete, Delete, new { id = item.CategoryID })%>
</td>
<td>
<%: item.CategoryID %>
</td>
<td>
<%: item.CategoryName %>
</td>
<td>
<%: item.Description %>
</td>
</tr>
<% } %>

</table>

</asp:Content>

O Controller

namespace AppCapitulo4.Controllers
{
public class CategorieController : Controller
{
CategoriesRepository _db = new CategoriesRepository();

public ActionResult Index()
{
var model = _db.GetAllCategories();
if (model == null)
return View(NotFound);
else
return View(model);
}

}
}

O Global ASAX

namespace AppCapitulo4
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801

public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(.axd/{*pathInfo});

routes.MapRoute(
Default, // Route name
//, // URL with parameters
new { controller = Categorie, action = Index, id = UrlParameter.Optional } // Parameter defaults
);

}

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();

RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}

O WEB Config

<connectionStrings>
<add name=nwind connectionString=Data Source=.\SQLExpress;Integrated Security=SSPI;Initial Catalog=northwind/>
</connectionStrings>
Responder

07/03/2012

Rodrigo Odasaki

Olá,

Vamos por parte.


Por padrão no ASP.NET MVC ele já vem com uma rota padrão sendo:

Controler / Action / Id

A url dele: localhost/AppCapitulo4/Categorie
Então AppCapitulo4 deve ser a controler
E Categorie deve ser a action

Você comentou sobre o erro que recebe vindo do IIS, qual é o erro?
Alias, você está rodando o projeto direto por um servidor IIS, ou está rodando no Start Debugging do visual studio?
Responder

08/03/2012

Pjava

Descobri o erro e não é culpa do livro que eu comprei. Fui precipitado em fazer críticas e por isso peço desculpas à editora NOVATEC. Errar dizem ser humano, mas errar precipitadamente acho que não, é no mínimo deselegante e me considerei nessas circunstâncias, deselegante. desculpa-me mais uma vez.

O erro estava em eu não colocar essa linha:

lst.add(p);
Responder

Assista grátis a nossa aula inaugural

Assitir aula

Saiba por que programar é uma questão de
sobrevivência e como aprender sem riscos

Assistir agora

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar