我正在 ASP.Net MVC(初学者)中从 ASP.Net 中的旧应用程序开发一个新应用程序,并且有一个查询:如何将下面的代码行转换为 MVC 中的新代码行?
HTML:
<div runat="server" id="dvLogList"></div>
.cs:
dvLogList.InnerHtml = sb.ToString()
我需要将 StringBuilder
附加的 string
html
代码设置为 dvLogList
innerhtml
最佳答案
您可以强类型化您的 View 。
作为示例,我有一个模型:
class DisplayModel
{
public string str { get; set; }
}
在我的 Controller 中,我会将这个模型传递给我的 View :
public ActionResult Display()
{
DisplayModel model = new DisplayModel
{
str = sb.ToString()
}
return View(model);
}
下一步是使我的 View 强类型化。为了实现这一点,请将此行添加到顶部
@model DisplayModel // Most of the cases you need to include the namespace to locate the class
<div id="dvLogList">@Model.str</div> // now your model is accessible in view
最后,我们为什么要这样做? 与使用 viewbag 相比,这具有优势,因为在某些情况下我们需要将数据回发到 Controller 。您 View 中的值会自动绑定(bind)到您的模型(假设您在操作中声明了模型)。
// model is automatically populated
public ActionResult Save(DisplayModel model)
{
}
有关更多知识,请阅读此链接我无法抽出更多时间来改进此答案 Strongly Typed Views
关于c# - 如何在 MVC Controller 中通过其 Id 使用 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40757469/