My UI does not reflect changes to my Model

时间:2016-05-17 11:15:32

标签: asp.net asp.net-mvc

I have a ASP MVC web app.

I have a partial form and it initally displays 'Hello Andy!'. I press the submit button and I change this to 'Hello Andy Again!. I pass the model back to the UI. The label still shows the old value.

Why?

My markup:

@using (Ajax.BeginForm("SaveAlertPreferences", "Users", new AjaxOptions
{
    UpdateTargetId = "partialform",
    InsertionMode = InsertionMode.Replace,
    HttpMethod = "POST",
{
    <div>
        @Html.AntiForgeryToken()
        <div class="section group">
            <div class="col span_3_of_12">
                @Html.LabelFor(model => model.myStub)
            </div>
            <div class="col span_9_of_12">
                @Html.TextBoxFor(model => model.myStub)
            </div>
        </div>

        <div class="section group">
            <div class="col span_3_of_12">
            </div>
            <div class="col span_4_of_12">
                <input type="submit" value="Press me" />
            </div>
            <div class="col span_5_of_12">
            </div>
        </div>
    </div>
}

My Model:

public class ChangeAlertPreferencesModel
{
    public string myStub { get; set; }
}

My Controller:

[AcceptVerbs("HEAD", "GET")]
public PartialViewResult _ChangeAlertPreferences()
{
    Response.CacheControl = "no-cache";

    ChangeAlertPreferencesModel m = new ChangeAlertPreferencesModel();
    m.myStub = "Hello Andy!";
    return PartialView("_ChangeAlertPreferences", m); 
}

[HttpPost]
public PartialViewResult SaveAlertPreferences(ChangeAlertPreferencesModel m)
{
    Response.CacheControl = "no-cache";
    if (ModelState.IsValid)
    {
        m.myStub = "Hello Andy Again!";
        return PartialView("_ChangeAlertPreferences", m);
    }
    else
    {
        m.myStub = "I have errored!";
        return PartialView("_ChangeAlertPreferences", m);
    }
    return null;
}

1 个答案:

答案 0 :(得分:0)

要完成我的评论,您的表单语句看起来很奇怪,所以您可能想尝试一下:

@using (Ajax.BeginForm("SaveAlertPreferences", "Users", new AjaxOptions
{
    UpdateTargetId = "partialform",
    InsertionMode = InsertionMode.Replace,
    HttpMethod = "POST",
}))
{

        @Html.AntiForgeryToken()
        <div class="section group">
            <div class="col span_3_of_12">
                @Html.LabelFor(model => model.myStub)
            </div>
            <div class="col span_9_of_12">
                @Html.TextBoxFor(model => model.myStub)
            </div>
        </div>

        <div class="section group">
            <div class="col span_3_of_12">
            </div>
            <div class="col span_4_of_12">
                <input type="submit" value="Press me" />
            </div>
            <div class="col span_5_of_12">
            </div>
        </div>
}

要解释,在第一行中,using部分声明了表单及其行为方式,然后结束(关闭)该声明并打开应该包含表单主体的块。