para las salidas de instrucciones de bucle que enlazan con diferentes controladores en asp.net mvc

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

  •  05-07-2019
  •  | 
  •  

Pregunta

Tengo una declaración de bucle en mi página de inicio para noticias ...

Tengo estos 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>

la sentencia for loop genera diferentes noticias desde diferentes controladores y vistas. Ejemplo, la primera salida podría mostrar esta página: Community / CommunityNews / 7 la segunda salida podría mostrar esta página: Atletismo / AtletismoNoticias / 5 la tercera salida podría mostrar esta página: Programs / ProgramsNews / 2

¿Cómo puedo hacer el código para el enlace a esas páginas? ¿Usaré javascript? el problema es que no estoy tan familiarizado con javascript :( ayuda por favor.. ¡gracias! gracias!

¿Fue útil?

Solución

Debería poder generar el segundo argumento para el método ActionLink, basado en un campo de tipo de noticias o similar en su tabla. por ejemplo

<%
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})%>

Esto debería hacer el truco, pero me empezaría a preocupar que haya mucho código en la vista. Puede que no sea una buena idea pasar DataTables como su modelo, pero podría requerir mucho trabajo cambiarlo en este momento.

Podría crear un método auxiliar que devolverá el controlador y la acción para un determinado tipo de noticias, o mejor aún, generará un enlace dado el tipo de noticia. Puede hacerlo creando una clase con métodos de extensión para la clase HtmlHelper. Ese método sería similar a este:

<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

Buena suerte. Creo que hay menos gente que usa VB.NET que C # con MVC.

Otros consejos

Supongo que esta parte de tu código de vista es donde tienes un problema?

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

El DBNull.Value se ve realmente extraño. ¿Quiso decir Null ?

De todos modos, deberías poder usar una sobrecarga como esta:

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

No uses JavaScript para esto.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top