来自 Ajax.BeginForm 的响应没有新的模型值

Response from Ajax.BeginForm not coming with new model values

我有一个 asp.net mvc 应用程序,但在 post 填写表单后遇到了一些问题。在动作中,我正在创建一个新模型,我在动作结束时 return。问题是传递的模型与 post 之前的值相同(我在 chrome 开发人员工具中检查过) 这是代码:

控制器:

public class TestController : Controller
    {
        public ActionResult Index()
        {
            return View(new MyViewModel());
        }

        [HttpPost]
        public virtual ActionResult GetScore(MyViewModel userInputDetails)
        {
            userInputDetails.Name = "Meeee";
            userInputDetails.Gender = "Yes Please!";
            return PartialView("_MyPartialView", userInputDetails);
        }
    }

Index.cshtml:

<div class="container">
    <div class="row">
        <div class="col-md-12">
            @using (Ajax.BeginForm("GetScore", "Test", new AjaxOptions()
                {
                    InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace,
                    HttpMethod = "POST",
                    UpdateTargetId = "partialResult"
                }))
            {        
                <div id="partialResult">
                    @Html.Partial("_MyPartialView", Model)
                </div>    
            }
        </div>
    </div>
</div>

_MyPartialView.cshtml

@model MvcAjaxUpdateTest.ViewModels.MyViewModel

<table class="table table-bordered" >
    <thead>
        <tr>
            <td>A1</td>
        </tr>
        <tr>
            <td>A2</td>
        </tr>
        <tr>
            <td>A2</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>@Html.TextBoxFor(m => m.Name)</th>
        </tr>
        <tr>
            <th>@Html.TextBoxFor(m => m.Gender)</th>
        </tr>
        <tr>
            <th><input type="submit" name="Go" /></th>
        </tr>
    </tbody>
</table>

"MyViewModel.cs"

public class MyViewModel
{
    public string Name { get; set; }

    public string Gender { get; set; }
}

您需要在更改已回发的值后在您的控制器方法中执行 ModelState.Clear()。否则视图将继续显示来自回发的 ModelState 的值,即使模型中的值不同。

请记住,这也会清除任何模型错误,因此请确保将其全部包装在 if(ModelState.IsValid){ }

即:

public class TestController : Controller
    {
        public ActionResult Index()
        {
            return View(new MyViewModel());
        }

        [HttpPost]
        public ActionResult GetScore(MyViewModel userInputDetails)
        {
            if (ModelState.IsValid)
            {
                userInputDetails.Name = "Meeee";
                userInputDetails.Gender = "Yes Please!";
                ModelState.Clear();
            }
            return PartialView("_MyPartialView", userInputDetails);
        }
    }

或者,您可能只需从 ModelState 中删除这些值即可。

即:

userInputDetails.Name = "Meeee";
userInputDetails.Gender = "Yes Please!";
ModelState.Remove("Name");
ModelState.Remove("Gender");