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

本文关键字:模型 Ajax BeginForm 响应 来自 | 更新日期: 2023-09-27 18:36:29

我有一个 asp.net 的 mvc 应用程序,发布表单后遇到了一些问题。在操作中,我正在创建一个新模型,并在操作结束时返回。问题是传递的模型具有与帖子之前相同的值(我在 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>

"我的视图模型.cs"

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

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

更改

已回发的值后,需要在控制器方法中执行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");