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

时间:2015-01-06 12:26:12

标签: c# ajax asp.net-mvc

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

&#34; MyViewModel.cs&#34;

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

    public string Gender { get; set; }
}

1 个答案:

答案 0 :(得分:1)

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

请记住,这也会清除任何ModelErrors,因此请确保将其全部包含在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");
相关问题