0

我有一个模板编辑器,Currency.cshtml如下所示:

@model decimal?
...
string value =
// Some calculations that returns value formatted as currency

Currency: @value<br/>
@Html.TextBox("", value, attributes)

我有一个使用这个模板的视图,如下所示:

@Html.EditorFor(m => m.Amount.Value, "Currency", someAdditionalViewData)

当此视图直接在另一个视图中呈现为部分视图时,结果符合预期:文本和编辑器都显示格式化变量“值”,如下所示:

Currency: 1.223,18   <== well formatted
[         1.223,18]  <== this is the input type=text, well formatted

但是,如果我使用 Ajax ( Ajax.ActionLink) 获取视图,我会格式化第一部分,但第二部分未格式化,如下所示:

Currency: 1.223,18   <== well formatted
[          1223.18]  <== this is the input type=text, not formatted!!

知道为什么会这样吗?@Html.TextBox("", value, attributes)我应该将模板中的final更改为其他内容吗?

4

2 回答 2

0

我不知道原因,但是在调查了一段时间后,我可以确保@Html.TextBox("", value, attributes)在 Ajax 请求上对 , 的最终调用的行为方式与在 PartialView 渲染上的行为方式不同。

在 PartialView 渲染中,它使用提供的格式化值创建所需的输入元素。但是,在 ajax 请求中,它会查找有关模型的信息并创建自己的文本框版本,包括不显眼的验证属性等。

解决这个问题的唯一方法是不使用该TextBox方法,而是创建一个输入直接用TagBuilder. 注意获取输入元素的Id和名称的方式。

@{
string value = ... // Format as desired

// Create the required attributes
// NOTE: HtmlAttributes is simply a custom "fluent" attribute builder, 
// inherited from IDictionay<string,object>
var attributes = HtmlAttributes.Empty
    .Add("type", "text")
    .Add("value", value) // formatted value
    .Add("id", ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(""))
    .Add("name", ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(""))
    .AddStyle("text-align", "right");

// You can add extra attributes, i.e. unobtrusive validation, provided by user...
var extraAttibutes = ...
attributes.Merge(extraAttributes);

// Use the tag builder to create the input
TagBuilder tb = new TagBuilder("input");
foreach (var attribute in attributes)
{
    tb.Attributes.Add(attribute.Key, attribute.Value.ToString());
}
var textBox = tb.ToString(TagRenderMode.SelfClosing);

// Then, either write it directly to the writer...
ViewContext.Writer.Write(textBox);
}
@* ...or use Html.Raw *@
@Html.Raw(textBox)

当然,还有很多细节被省略(如何获得不显眼的标签或任何其他额外的标签属性等等)。最好的办法是发现为什么行为会从“完整”渲染和 ajax 请求渲染发生变化。所有 View 元数据看起来完全相同,但工作方式不同。

于 2013-06-18T09:56:09.960 回答
0

我还有一个使用编辑器模板的部分视图,该模板在最初加载页面时起作用。但是,当使用 ajax 调用部分时,没有使用编辑器模板。

对我来说,我不得不将它移动到另一个文件夹:

来自 Views/[Controllername]/EditorTemplates

视图/共享/编辑器模板

于 2015-08-06T12:15:23.833 回答