The first time I came up against this, I came up with an onclick()/JavaScript hack when choices are not prev/next that I still like for its simplicity. 它是这样的:
@model myApp.Models.myModel
<script type="text/javascript">
function doOperation(op) {
document.getElementById("OperationId").innerText = op;
// you could also use Ajax to reference the element.
}
</script>
<form>
<input type="text" id = "TextFieldId" name="TextField" value="" />
<input type="hidden" id="OperationId" name="Operation" value="" />
<input type="submit" name="write" value="Write" onclick='doOperation("Write")'/>
<input type="submit" name="read" value="Read" onclick='doOperation("Read")'/>
</form>
当单击任一提交按钮时,它将所需的操作存储在隐藏字段中(这是包含在与表单关联的模型中的字符串字段)并将表单提交给控制器,控制器完成所有决定。在 Controller 中,您只需编写:
// Do operation according to which submit button was clicked
// based on the contents of the hidden Operation field.
if (myModel.Operation == "Read")
{
// Do read logic
}
else if (myModel.Operation == "Write")
{
// Do write logic
}
else
{
// Do error logic
}
您也可以使用数字操作代码稍微加强这一点,以避免字符串解析,但除非您使用枚举,否则代码的可读性、可修改性和自记录性较差,而且解析是微不足道的。