所以,标题应该不言自明。

在ASP中创建可重用的组件。NET MVC,我们有3个选项(可能是其他我没有提到的):

局部视图:

@Html.Partial(Model.Foo, "SomePartial")

定制编辑器模板:

@Html.EditorFor(model => model.Foo)

自定义显示模板:

@Html.DisplayFor(model => model.Foo)

就实际的View/HTML而言,所有三种实现都是相同的:

@model WebApplications.Models.FooObject

<!-- Bunch of HTML -->

所以,我的问题是——何时/如何决定使用三种方法中的哪一种?

我真正想要的是在创建一个之前问自己的问题列表,答案可以用来决定使用哪个模板。

以下是我发现EditorFor/DisplayFor更好的2件事:

They respect model hierarchies when rendering HTML helpers (e.g if you have a "Bar" object on your "Foo" model, the HTML elements for "Bar" will be rendered with "Foo.Bar.ElementName", whilst a partial will have "ElementName"). More robust, e.g if you had a List<T> of something in your ViewModel, you could use @Html.DisplayFor(model => model.CollectionOfFoo), and MVC is smart enough to see it's a collection and render out the single display for each item (as opposed to a Partial, which would require an explicit for loop).

我也听说过DisplayFor呈现一个“只读”模板,但我不明白-我不能扔一个表单在那里吗?

有人能告诉我其他原因吗?有没有比较这三个的列表/文章?

我想在一个视图中有2个模型。页面包含LoginViewModel和RegisterViewModel。

e.g.

public class LoginViewModel
{
    public string Email { get; set; }
    public string Password { get; set; }
}

public class RegisterViewModel
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
}

我需要做另一个ViewModel持有这2个ViewModel吗?

public BigViewModel
{
    public LoginViewModel LoginViewModel{get; set;}
    public RegisterViewModel RegisterViewModel {get; set;}
}

我需要将验证属性带到视图中。这就是为什么我需要ViewModels。

有没有其他的方法,比如(没有BigViewModel):

 @model ViewModel.RegisterViewModel
 @using (Html.BeginForm("Login", "Auth", FormMethod.Post))
 {
        @Html.TextBoxFor(model => model.Name)
        @Html.TextBoxFor(model => model.Email)
        @Html.PasswordFor(model => model.Password)
 }

 @model ViewModel.LoginViewModel
 @using (Html.BeginForm("Login", "Auth", FormMethod.Post))
 {
        @Html.TextBoxFor(model => model.Email)
        @Html.PasswordFor(model => model.Password)
 }

我想有2个单独的布局在我的应用程序。让我们说一个是为网站的公共部分,另一个是为会员方。

为了简单起见,我们假设每个站点的所有逻辑都被整齐地包装在两个不同的控制器中。

PublicController StaffController

它们每个都有一个对应的视图布局。

_PublicLayout.cshtml _StaffLayout.cshtml

我如何使用_ViewStart。cshtml文件指定“公共”下的所有视图/操作使用的PublicLayout和“人员”下的一切使用的StaffLayout?

我遇到了一个问题,将存储在数据库中的文件发送回ASP中的用户。净MVC。我想要的是一个列出两个链接的视图,一个用于查看文件并让发送到浏览器的mimetype决定如何处理它,另一个用于强制下载。

如果我选择查看一个名为SomeRandomFile.bak的文件,而浏览器没有相关的程序来打开这种类型的文件,那么它默认为下载行为就没有问题。但是,如果我选择查看名为SomeRandomFile.pdf或SomeRandomFile.jpg的文件,我希望该文件直接打开。但是我还想在旁边保留一个下载链接,这样无论文件类型如何,我都可以强制下载提示。这有道理吗?

我已经尝试了FileStreamResult,它适用于大多数文件,它的构造函数默认不接受文件名,因此未知文件被分配一个基于URL的文件名(不知道扩展名基于内容类型)。如果我强制指定文件名,浏览器就不能直接打开文件,只能得到下载提示。有人遇到过这种情况吗?

这些是我目前为止尝试过的例子。

//Gives me a download prompt.
return File(document.Data, document.ContentType, document.Name);

//Opens if it is a known extension type, downloads otherwise (download has bogus name and missing extension)
return new FileStreamResult(new MemoryStream(document.Data), document.ContentType);

//Gives me a download prompt (lose the ability to open by default if known type)
return new FileStreamResult(new MemoryStream(document.Data), document.ContentType) {FileDownloadName = document.Name};

有什么建议吗?


UPDATE: This questions seems to strike a chord with a lot of people, so I thought I'd post an update. The warning on the accepted answer below that was added by Oskar regarding international characters is completely valid, and I've hit it a few times due to using the ContentDisposition class. I've since updated my implementation to fix this. While the code below is from my most recent incarnation of this problem in an ASP.NET Core (Full Framework) app, it should work with minimal changes in an older MVC application as well since I'm using the System.Net.Http.Headers.ContentDispositionHeaderValue class.

using System.Net.Http.Headers;

public IActionResult Download()
{
    Document document = ... //Obtain document from database context

    //"attachment" means always prompt the user to download
    //"inline" means let the browser try and handle it
    var cd = new ContentDispositionHeaderValue("attachment")
    {
        FileNameStar = document.FileName
    };
    Response.Headers.Add(HeaderNames.ContentDisposition, cd.ToString());

    return File(document.Data, document.ContentType);
}

// an entity class for the document in my database 
public class Document
{
    public string FileName { get; set; }
    public string ContentType { get; set; }
    public byte[] Data { get; set; }
    //Other properties left out for brevity
}

我目前有两个不相关的MVC3项目托管在线。

一个工作正常,另一个不工作,给我一个错误:

发现了与名为“Home”的控制器匹配的多种类型。这 如果服务此请求的路由会发生什么 ('{controller}/{action}/{id}')不指定要搜索的名称空间 与请求匹配的控制器。 如果是这样的话, 通过调用'MapRoute'方法的重载来注册这个路由 它接受一个“namespaces”参数。

我的主机的工作方式是,他给我FTP访问权限,在这个文件夹中,我有另外两个文件夹,一个用于我的应用程序。

ftpFolderA2 - foo。com ftpFolderA2 / bar。com

foo.com工作正常,我发布我的应用程序到我的本地文件系统,然后FTP内容,它工作。

当我上传并尝试运行bar.com时,上面的问题触发并阻止我使用我的网站。同时,foo.com还在运作。

是bar.com搜索从ftpFolderA2内部的控制器,这就是为什么它正在寻找另一个HomeController?我怎么能告诉它只看在控制器文件夹,因为它应该?

事实:

不使用区域。这是两个完全不相关的项目。我将每个已发布的项目放入各自的文件夹中。没有什么幻想。 每个项目只有1个HomeController。

有人能确认是这个问题吗?

HTML和HTML有什么区别吗?ActionLink vs Url。行动还是它们只是做同一件事的两种方式?

什么时候我应该选择其中一个而不是另一个?

我在MVC 3中看到了ViewBag。这和MVC 2中的ViewData有什么不同?

我有一个输入文本是这样的:

<div class="editor-label">
    @Html.LabelFor(model => model.EmployeeId, "Employee Number")
</div>

<div class="editor-field textBoxEmployeeNumber">
    @Html.EditorFor(model => model.EmployeeId) 
    @Html.ValidationMessageFor(model => model.EmployeeId)
</div>

生成以下html

< div class = " editor-label”> <label for="EmployeeId">员工号</label> . < / div > <div class="editor-field textBoxEmployeeNumber"> <input class="text-box single-line" data-val="true" data-val-number="The field EmployeeId must be a number." data-val-required="The EmployeeId field is required." id="EmployeeId" name="EmployeeId" type="text" value="" /> . <span class="field-validation-valid" data-valmsg-for="EmployeeId" data-valmsg-replace="true"></span> . < / div >

我想用jquery设置这个输入文本的值,所以我这样做:

<script type="text/javascript" language="javascript">
    $(function() {
        $('.textBoxEmployeeNumber').val("fgg");
    });
</script> 

然而,它并没有起作用…我的语法有什么错误?

我在我的_Layout.cshtml中定义了这个部分

@RenderSection("Scripts", false)

我可以很容易地从视图中使用它:

@section Scripts { 
    @*Stuff comes here*@
}

我正在努力解决的问题是如何从局部视图将一些内容注入到这个部分中。

让我们假设这是我的视图页面:

@section Scripts { 

    <script>
        //code comes here
    </script>
}

<div>
    poo bar poo
</div>

<div>
  @Html.Partial("_myPartial")
</div>

我需要在脚本部分中从_myPartial partial视图中注入一些内容。

我该怎么做呢?

为什么需要Json请求行为?

如果我想限制HttpGet请求到我的动作,我可以用[HttpPost]属性装饰这个动作

例子:

[HttpPost]
public JsonResult Foo()
{
    return Json("Secrets");
}

// Instead of:
public JsonResult Foo()
{
    return Json("Secrets", JsonRequestBehavior.AllowGet);
}

为什么[HttpPost]不是充分的? 为什么框架用JsonRequestBehavior“bug”我们。AllowGet为每个JsonResult。如果我想拒绝get请求,我会添加HttpPost属性。