2

如何在某些特定 div 中呈现部分视图而不在 asp.net mvc 3 中使用 ajax?

例如我有一个模型:

public class TestViewModel
{
    public string FullText
    {
        get
        {
            retrun "Full text";
        }
    }
    public string ShortText
    {
        get
        {
            return "Short text";
        }
    }
}

主视图:

@model TestViewModel
   ...      
    <div id="RenderHere">

    </div>
    @Html.ActionLink("Show short text");
    @Html.ActionLink("Show full text");
   ...

和两个部分视图:

ShortTextParial

@model TestViewModel
@Html.LabelFor(m => m.ShortText);
@Model.ShortText;

和全文部分

@model TestViewModel
@Html.LabelFor(m => m.FullText);
@Model.FullText;

例如,在不使用 ajax 的情况下按下“显示短文本”操作链接后,如何在“RenderHere”div 中呈现 ShortTextPartial?我已经找到了这样的解决方案,但它们不适合我。

PS 我不想使用 Ajax,因为如果在客户端禁用 Java 脚本,页面将无法正常工作。

4

2 回答 2

2

First of all I have to say I don't think your design is the best. Please notice that most of the logics, comparisons, and conditions should take place in your Models and Business Logic tier, rather than in Views and Controllers.

Anyway, If you don't want to use AJAX, you should either use URL parameters or Session States to pass data between pages. Having said that, I developed it by URL parameters.

(My development environment is VS2010 SP1, ASP.NET 4, MVC 3)

First we need to change TextViewModel like this:

public class TextViewModel
{
    public string FullText { get { return "Full text"; } }
    public string ShortText { get { return "Short text"; } }

    public string ViewMode { get; private set; }

    public TextViewModel(string viewMode)
    {
        if (!string.IsNullOrWhiteSpace(viewMode))
            this.ViewMode = viewMode.Trim().ToLower();
    }
}

Now a little tweak on Controller:

public class HomeController : Controller
{
    public ActionResult Index(string id)
    {
        Models.TextViewModel model = new Models.TextViewModel(id);
        return View(model);
    }
}

and finally our view:

@model MvcApplication1.Models.TextViewModel
@{
    ViewBag.Title = "Index";
}
<h2>
    Index</h2>
<div id="RenderHere">
    @if (Model.ViewMode == "short")
    {
        @Html.Partial("ShortTextParial", Model)
    }
    @if (Model.ViewMode == "full")
    {
        @Html.Partial("FullTextPartial", Model)
    }
</div>
@Html.ActionLink("Show short text", "Index", new { id = "short" })
@Html.ActionLink("Show full text", "Index", new { id = "full" })

The application works well in my computer. I've uploaded the code here if you need it: http://goo.gl/9v2Ny

Again I want to say you can come up with a better design which doesn't need any @if in the View or even in the Controller.

于 2012-06-15T21:21:28.110 回答
0

如果您真的不想使用 ajax 显示更多数据,您可以在单独的 div 中加载这两个内容并隐藏完整视图,当用户单击“显示更多”链接时,只需显示它。

你真的想这样做吗?请记住,并非所有用户都会点击您的“显示更多”链接。您仍然会为用户加载内容并将其隐藏。为什么需要这样做并增加页面大小?如果可能的话,我会使用 ajax 解决方案来“按需”提供数据。

于 2012-05-28T00:21:29.917 回答