0
我在Web窗体项目中使用用户控件。这是一个遗留项目,但我们从ASP.NET MVC中获得了很多灵感,并将其纳入了我们的项目。如何从ASPX标记代码中的用户控件Inherits模型中访问对象
我嵌入了一个用户控件,而不是旧的“usercontrol-can-do-everything”,我们更多地使用它们作为partials并给它们一个viewmodel。
但是,我在代码中访问我的“viewmodel”中的值时出现问题。让我展示一些代码,我会解释问题。
控制定义:
<%@ Control Language="vb" AutoEventWireup="false" Inherits="Saxo.Websites.Shop.Web.PartialControl`1[[Saxo.Websites.Shop.Models.Recommendations.RecommendationsViewModel]]" %>
我的 “视图模式”:
public class RecommendationsViewModel
{
public Dictionary<string, Placement> Placements { get; set; }
public RecommendationsViewModel()
{
this.Placements = new Dictionary<string, Placement>();
}
}
public class Placement
{
public Placement(string divid, string title):this(divid,title,6)
{
}
public Placement(string divid, string title, int count)
{
this.DivId = divid;
this.Title = title;
this.Count = count;
}
public string DivId { get; set; }
public string Title { get; set; }
public int Count { get; set; }
}
我partialcontrol文件:
public class PartialControl<T> : UserControl
{
public T Model { get; set; }
public static string RenderPartial(string path, object model)
{
var control = new UserControl();
try
{
control = (UserControl)control.LoadControl(path);
}
catch (Exception ex)
{
throw new ApplicationException("Error loading partial control: " + path, ex);
}
var prop = control.GetType().GetProperty("Model");
if (prop == null)
{
throw new ApplicationException(control.GetType().FullName + " does not implement Property 'Model'");
}
try
{
prop.SetValue(control, model, null);
}
catch (Exception)
{
throw new ApplicationException("Error setting model on : " + control.GetType().FullName);
}
using (var sw = new StringWriter())
{
using (var hw = new HtmlTextWriter(sw))
{
try
{
control.RenderControl(hw);
return sw.ToString();
}
catch (Exception ex)
{
throw new ApplicationException("Error Rendering Partial Control: " + control.GetType().FullName, ex);
}
}
}
}
}
现在,我要做到以下几点在我的标记:像<%
和<%#
<script charset="utf-8" type="text/javascript">
var test = '<%= Model.Placements["key_in_my_dictionary"].Title %>';
</script>
我也试过变种。
不过,我得到这个错误:
System.Web.HttpCompileException: D:\Git\Saxo\Saxo.Websites.Base\src\Saxo.Website.Base\Views\Recommendations\_PageRecommendations.ascx(38): error BC30203: Identifier expected.
,但我可以做成功了以下内容:
<script charset="utf-8" type="text/javascript">
var test = '<%= Model.Placements.Count %>';
</script>
因此,我的问题是:我怎么写我的标记,所以我的JS变量测试获得标题值?
这将工作,唯一的问题是它的实现方式,是不存在的代码BEH ind在用户控件中。事实证明,错误是由我的前端是VB.NET而不是C#(wtf?:D)造成的。但我会将您的答案标记为答案,因为当人们通过Google找到答案时,这是最好的方式。 – 2014-09-07 16:36:46