asp.net-mvc-3 – 如何在razor视图中设置@ model.attribute?
我有一个必填字段,字符串属性{get; set}并且想要在razor中设置它的值。是类似下面的可能吗?
@model.attribute = "whatever' 解决方法
首先,资本化重要。
@model(小写字母“m”)是Razor视图中的保留关键字,用于在视图顶部声明模型类型,例如: @model MyNamespace.Models.MyModel 稍后在文件中,可以使用@ Model.Attribute(大写“M”)引用所需的属性。 @model声明模型。模型引用模型的实例化。 第二,您可以为模型分配一个值,然后在页面中使用它,但是当页面提交到控制器操作时,它不会持久,除非它是表单字段中的值。为了在模型绑定过程中将值返回到模型中,您需要将值分配给表单字段,例如: 选项1 在控制器动作中,您需要为页面的第一个视图创建一个模型,否则当您尝试设置Model.Attribute时,Model对象将为null。 控制器: // This accepts [HttpGet] by default,so it will be used to render the first call to the page public ActionResult SomeAction() { MyModel model = new MyModel(); // optional: if you want to set the property here instead of in your view,you can // model.Attribute = "whatever"; return View(model); } [HttpPost] // This action accepts data posted to the server public ActionResult SomeAction(MyModel model) { // model.Attribute will now be "whatever" return View(model); } 视图: @{Model.Attribute = "whatever";} @* Only do this here if you did NOT do it in the controller *@ @Html.HiddenFor(m => m.Attribute); @* This will make it so that Attribute = "whatever" when the page submits to the controller *@ 选项2 或者,由于模型是基于名称的,因此可以跳过在控制器中创建模型,并且只需为表单字段命名与模型属性相同的名称。在这种情况下,将名为“Attribute”的隐藏字段设置为“whatever”将确保在页面提交时,值“whatever”将在模型绑定过程中绑定到模型的Attribute属性。注意,它不必是一个隐藏字段,只是任何具有name =“Attribute”的HTML输入字段。 控制器: public ActionResult SomeAction() { return View(); } [HttpPost] // This action accepts data posted to the server public ActionResult SomeAction(MyModel model) { // model.Attribute will now be "whatever" return View(model); } 视图: @ Html.Hidden(“Attribute”,“whatever”); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net – 有没有= window.onload在Javascript?
- asp.net简单生成XML文件的方法
- asp.net-mvc – 是否可以使用RedirectToAction清除路由值?
- 给ASP.NET Core Web发布包做减法
- asp.net – Web Farm上的Forms Authentication 4.0
- asp.net-mvc – ASP.NET MVC中基础控制器类的好候选人是什么
- asp.net – 在项目之间共享aspx页面
- jQuery Ajax方法调用 Asp.Net WebService 的详细实例代码
- 使用 Xunit.DependencyInjection 改造测试项目
- asp.net-mvc – 确保视图存在
- ASP.Net Core 2.0 Webapi设置了log4net
- 在viewstate(或其他想法)中的asp.net商店对象类
- asp.net – 如何将Enter键与aspx页面上的按钮相关
- asp.net – SQL Server 2008中的Bool类型
- asp.net – Combres的路线(combres.axd)不起作用
- asp.net – 为什么浮动元素中的浮动控件在IE7中向
- asp.net-mvc – 在Html.TextBoxFor()onchange事件
- asp.net-mvc – Bug? ASP.NET MVC 2中的客户端验
- asp.net-mvc – 处理MVC中的无效URL
- Pro ASP.NET Core MVC(一)【前世今生】