loop for comunicado saídas que links para diferentes controladores no asp.net MVC

StackOverflow https://stackoverflow.com/questions/1611655

  •  05-07-2019
  •  | 
  •  

Pergunta

Eu tenho uma instrução de loop no em minha página inicial para a notícia ..

Eu tenho esses códigos ..

Modelo:

Imports Microsoft.VisualBasic
Imports System.Data

Public Class ClassNewsConnection

    Inherits ClassConnection

    'Featured News for Home Page

    Public Function NewsFeatureHome() As DataTable
        Return ReadData("SELECT * FROM news WHERE newsFeature = '" & 1 & "' ORDER BY newsID DESC LIMIT 3  ")
    End Function


End Class

Controlador:

Public Class HomeController
    Inherits Global.System.Web.Mvc.Controller
    Private News As New ClassNewsConnection
    Private Announcement As New ClassAnnouncementConnection
    Private Process As New ClassHTML

Function Index() As ActionResult
        Dim dNews As DataTable = News.NewsFeatureHome()

        For dCount As Integer = 0 To dNews.Rows.Count - 1
            dNews.Rows(dCount).Item("newsTitle") = Process.ToHTML(dNews.Rows(dCount).Item("newsTitle"))
            dNews.Rows(dCount).Item("newsContent") = Process.ToHTML(dNews.Rows(dCount).Item("newsContent"))
        Next
        Return View(dData)
    End Function

End Class

Ver:

<%@ Page Title="" Language="VB" MasterPageFile="~/Views/Shared/SiteMasterPage.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%@ Import Namespace="System.Data" %>

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

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

    <h2>Index</h2>

    <div>

        <label for="News">News</label>
        <%Dim dNews As DataTable = ViewData.Model%>
        <%Dim id As Integer%>
        <%Dim dTitle As String%>

        <%For dCount As Integer = 0 To dNews.Rows.Count - 1%>
        <%Dim dContent As String = dNews.Rows(dCount).Item("newsContent")%>
        <%id = dNews.Rows(dCount).Item("newsID")%>

        <p>
        <%dTitle = dNews.Rows(dCount).Item("newsTitle")%>
        <%=Html.ActionLink(dTitle, "__________", New With {id}, DBNull.Value)%>
        <img src='<%=Url.Content("~/NewsImages/" + dNews.Rows(dCount).Item("newsThumbnail")) %>' alt="" />

        <%If dContent.Length > 100 Then%>
            <%dContent = dContent.Substring(0, dContent.IndexOf("", 300)) & "..."%>
        <%Else%>
            <%dContent = dContent%>
        <%End If%>

        <%=Html.ActionLink("Read More", "__________", New With {id}, DBNull.Value)%>
        </p>

        <%Next%>
    </div>

</asp:Content>

a instrução for circuito saídas notícias diferentes a partir de diferentes controladores e vistas .. Exemplo, A primeira saída poderia tornar esta página: Community / CommunityNews / 7 A segunda saída poderia tornar esta página: Atletismo / AthleticsNews / 5 a terceira saída poderia tornar esta página: Programas / ProgramsNews / 2

Como eu poderia tornar o código para o link para essas páginas? i vai usar javascript? o problema é, eu não sou tão tão familiarizado com javascript :( ajuda por favor.. obrigado! obrigado!

Foi útil?

Solução

Você deve ser capaz de gerar o segundo argumento para o método ActionLink, com base em um campo de tipo de notícia ou similar em sua mesa. por exemplo.

<%
Dim newsType As String = dNews.Rows(dCount).Item("newsType")

Dim controllerName As String
Dim actionName as String

' I'm guessing you have a field similar to this:
If (newsType = "Com. News") then
  controllerName = "Community"
  actionName = "CommunityNews"
End If

If (newsType = "Ath. News") then 
  controllerName = "Athletics"
  actionName = "AthleticsNews"
End If
%>

<%=Html.ActionLink(dTitle, actionName, controllerName, New With {Id = id})%>

Isso deve fazer o truque, mas eu gostaria de começar a se preocupar que está começando a ser muito código no modo de exibição. Pode não ser uma boa idéia para passar DataTables em como o modelo, mas poderia ter um monte de trabalho para mudar isso neste momento.

Você pode criar um método auxiliar que irá devolver o controlador e ação para um determinado tipo de notícias, ou melhor ainda, gerar um link dado o tipo de notícias. Você pode fazer isso através da criação de uma classe com métodos de extensão para a classe HtmlHelper. Esse método seria semelhante a esta:

<Extension()> _
Public Sub NewsLink(ByVal htmlHelper As HtmlHelper, newsType as string, linkText As String, id As int)

    Dim action As String
    Dim controller As String

    'todo: logic to get action and controller names from news type

    return htmlHelper.ActionLink(linkText, action, controller, New With {Id = id})
End Sub

Boa sorte. Eu acho que há menos pessoas usando VB.NET de C # com MVC.

Outras dicas

Eu suponho que esta parte do seu código de vista é onde você tem um problema?

Html.ActionLink(dTitle, "__________", New With {id}, DBNull.Value)

O DBNull.Value parece realmente estranho. Será que você Null média?

De qualquer forma, você deve ser capaz de usar uma sobrecarga como esta:

Html.ActionLink(dTitle, "CommunityNews", "Community", New With {id}, Null)

Não use JavaScript para isso.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top