[英]mvc3 - return bool from view to controller
Background 背景
I have a bool in a view model class. 我在视图模型类中有一个布尔。 I have an if statement checking to see if the bool is true or false.
我有一个if语句,检查布尔是对还是错。 If false I set the value to true and call a view.
如果为false,则将值设置为true并调用视图。 In the view I have button that when clicked updates and calls the view again.
在视图中,我有一个按钮,单击该按钮可以更新并再次调用该视图。 My problem is that the bool keeps being set to false when the view is loaded.
我的问题是,加载视图时,布尔值始终设置为false。 I don't know why this is happening.
我不知道为什么会这样。 Is there a way to stop the bool from being changed?
有没有办法阻止布尔值被更改?
Attempts 尝试次数
I'm aware MVC is stateless. 我知道MVC是无状态的。
The view I've been given to work with is a .aspx view with the "value" attribute of the input tag already being used. 我已使用的视图是一个.aspx视图,其输入标签的“值”属性已被使用。 So I'm unable to update the value of the Submit button.
因此,我无法更新“提交”按钮的值。
<input type="submit" class="button" value="bvCalc" />
Question 题
In whatever way, I'm looking to persist the state of the bool. 无论如何,我都希望保持布尔状态。 I don't know how to do this and I'm unsure as to whether or not the best thing to do at this point would be to
我不知道该怎么做,我不确定此时最好的做法是
The way values get from a view to controller is via ModelBinding
. 值从视图到控制器的获取方式是通过
ModelBinding
。 If you are not familiar with how this works you might like to Google it to get a better understanding. 如果您不熟悉此方法的工作原理,则可以通过Google对其进行更好的了解。
As a quick example, lets say the action method in your controller that you want to pass the bool to looks like this: 举个简单的例子,假设您要传递布尔值的控制器中的action方法如下所示:
public ActionResult MyAction(MyViewModel model)
{
//.. do something here.
}
and your ViewModel looks like this: 并且您的ViewModel看起来像这样:
public class MyViewModel
{
public bool MyBool { get; set; }
// ...more properties...
}
As long as your view has some kind of field (eg text box, checkbox, hidden field) with a name that exactly matches the property name (in this case 'MyBool') and a value that will convert to the property (in this example the string 'True' can map to to the boolean true
value) - ModelBinding
will be able to populate model.MyBool
with true
in your controller action. 只要您的视图具有某种字段(例如,文本框,复选框,隐藏字段),其名称与属性名称(在本例中为“ MyBool”)完全匹配,并且其值将转换为属性(在本示例中)字符串“ True”可以映射到布尔值
true
) ModelBinding
可以在您的控制器操作中填充model.MyBool
true
。
If you use the built-in helper methods, you don't need to worry about getting the correct name/value in your field element - MVC will do this for you 如果您使用内置的辅助方法,则无需担心在字段元素中获得正确的名称/值-MVC会为您完成此操作
eg @Html.HiddenFor(model => model.MyBool)
will render HTML something like 例如
@Html.HiddenFor(model => model.MyBool)
将呈现HTML类似
<input type="hidden" id="MyBool" name="MyBool" value="True" />
Use bool? 使用布尔? In your model.
在您的模型中。 Without it bool will always default to be false.
没有它,布尔将始终默认为false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.