[英]How to bind Div to Property on a model in MVC 3
我有以下视图模型,它将用于获取问题说明和重新创建问题的步骤。
public class IssueViewModel
{
public string IssueDesc { get; set; }
public string ReCreationSteps { get; set; }
}
视图
@using (Html.BeginForm())
{
@Html.LabelFor(model => model.IssueDescription)
@Html.TextAreaFor(m=>m.IssueDescription)
@Html.LabelFor(model => model.ReCreationSteps )
<div class="editable" id="ReCreationSteps " name="ReCreationSteps" contenteditable="true">
<ol>
<li></li>
</ol>
</div>
<input value="Create" type="submit" />
}
调节器
[HttpPost]
public ActionResult Create(IssueViewModel model)
{
string html = model.Recreation;
//<ol><li>Step:1 Enter the text</li><li>Step:2 Click the button <li></ol>
Issue newIssue = model.ToIssue(); // here value will be splitted and add steps to table
_issueRepository.AddIssue(Issue);
}
我想给用户一个简单的控件来输入问题重新创建步骤。因此,我最终将div元素的contenteditable属性设置为true。
我已经将ReCreationSteps绑定到Div元素,但是不起作用。提交表单后,我无法在ReCreationSteps属性中获取DIV的值/ html。
任何人都可以帮我解决这个问题或为我提供其他解决方案。
从我看来,您将需要使用“ AllowHtmlAttribute ”装饰模型并创建一个自定义扩展名,以便正确保存您的信息。
UPDATE
如果要创建扩展包装,可以执行以下操作:
扩展助手
public static class CustomExtensions {
public static IDisposable Step<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) {
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
TextWriter writer = html.ViewContext.Writer;
writer.WriteLine("<div class=\"editable\" id=\"Raw_{0}\" name=\"Raw_{0}\">", metadata.PropertyName);
var modelValue = metadata.Model == null ? "" : metadata.Model.ToString();
writer.WriteLine(modelValue);
writer.WriteLine("<input type=\"hidden\" id=\"{0}\" name=\"{0}\" value=\"{1}\"/>", metadata.PropertyName, html.Encode(modelValue));
return new CreationSteps(html, metadata);
}
private class CreationSteps : IDisposable {
#region | Properties |
private readonly TextWriter writer;
private bool disposed;
private ModelMetadata _metadata;
#endregion
/// <summary>
/// Initialize a new instance of <see cref="CreationSteps"/>
/// </summary>
/// <param name="html"></param>
/// <param name="metadata"></param>
public CreationSteps(HtmlHelper html, ModelMetadata metadata) {
this._metadata = metadata;
this.writer = html.ViewContext.Writer;
}
#region | Public Methods |
public void Dispose() {
if (disposed) return;
disposed = true;
writer.WriteLine("</div>");
}
#endregion
}
}
视图
@using (@Html.Step(m => m.HtmlValues)) {
<p>Please fill in the above information.</p>
}
模拟数据
<ol> <li> Step:1输入文本:<输入id =“ text1” class =“ hook-text-event” /> <li> Step:2单击按钮:<button id =“ button2” class = “ hook-button-event”>“我的按钮” <li>
JavaScript的
$(document).ready(function () {
$(".hook-text-event").change(function () {
console.log(this.id + " has been changed");
});
$(".hook-button-event").click(function () {
console.log(this.id + " has been clicked");
});
});
如果希望用户能够添加多个步骤(每个步骤一个<li>
),则需要使用JavaScript定义自定义表单。 那是你的计划吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.