在MVC中发布后模型没有绑定?

Rah*_*ury 0 c# asp.net-mvc

我正在尝试使用 from submit 对两个数字求和。HttpGet 工作正常,但在提交表单时,我无法在视图中显示它..

public class CalculatorController : Controller
    {
        //
        // GET: /Calculator/

        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public ActionResult Sum()
        {
            CalculatorModel model = new CalculatorModel();
            model.FirstOperand = 3;
            model.SecondOperand = 4;
            model.Result = model.FirstOperand + model.SecondOperand;
            //Return the result
            return View(model);
        }

        [HttpPost]
        public ActionResult Sum(CalculatorModel model)
        {
            model.Result = model.FirstOperand + model.SecondOperand;
            //Return the result
            return View(model);
        }

    }
Run Code Online (Sandbox Code Playgroud)
@model HTMLHelpersDemo.Models.CalculatorModel
@{
    ViewBag.Title = "Sum";
}

<h2>Sum</h2>

@using (Html.BeginForm("Sum", "Calculator", FormMethod.Post))
{
    <table border="0" cellpadding="3" cellspacing="1" width="100%">
        <tr valign="top">
            <td>
                @Html.LabelFor(model => model.FirstOperand)
                @Html.TextBoxFor(model => model.FirstOperand)
            </td>
        </tr>
        <tr valign="top">
            <td>
                @Html.LabelFor(model => model.SecondOperand)
                @Html.TextBoxFor(model => model.SecondOperand)
            </td>
        </tr>
        <tr valign="top">
            <td>
                @Html.LabelFor(model => model.Result)
                @Html.TextBoxFor(model => model.Result)
            </td>
        </tr>
    </table>
    <div style="text-align:right;">
        <input type="submit" id="btnSum" value="Sum values" />
    </div>
}
Run Code Online (Sandbox Code Playgroud)

最初它显示 7 为 3 加 4

但是当我更改我的值并发布它时它没有显示旧值..在控制器中调试它显示完美但没有发布以正确查看

Shy*_*yju 5

您需要从模型状态字典中清除先前的结果值。您可以使用该ModelState.Clear()方法来做到这一点。

[HttpPost]
public ActionResult Sum(CalculatorModel model)
{
    ModelState.Clear();
    model.Result = model.FirstOperand + model.SecondOperand;         
    return View(model);
}
Run Code Online (Sandbox Code Playgroud)