第一次遇到此问题时,我想到了onclick()/ JavaScript hack,因为它的简单性不是我喜欢的上一个/下一个选择。它是这样的:
@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
}
您也可以使用数字操作代码略微加强此功能,以避免字符串解析,但是除非您使用枚举,否则代码的可读性,可修改性和自文档性较低,并且无论如何解析都是微不足道的。