如何将修改后的模型传回视图?

时间:2010-11-09 23:19:34

标签: entity-framework asp.net-mvc-2 entity-framework-4

想象一下带有帖子的简单动作

public ActionResult Unsubscribe(string contentId)
{
    // get db content and translate it to the UnsubscribeViewModel
    UnsubscribeViewModel model = 
        myRepository.FindUnsubscribeContentById(contentId).ToUnsubscribeViewModel();

    // pass model into the view
    return View(model);
}

[HttpPost]
public ActionResult Unsubscribe(UnsubscribeViewModel model)
{
    // let's convert into DalModel
    UnsubscribeModel m = model.ToUnsubscribeModel();

    // let's save into the db
    myRepository.UpdateUnsubscribe(m);

    // because I'm using 2 models, let's get the new ID 
    // and append to he View model
    model.FieldId = m.unsubscribe_id;

    // let's return the new model to the View
    return View(model);
}

我当前的问题是,即使我在return View(model)行上执行断点,我有正确model.FieldId 已分配,但在HTML页面中,我有原始值(在这种情况下为0,因为没有先前的ID,这是一个新记录)

在我试过的视图中

<%: Html.HiddenFor(x => x.FieldId) %>

<%: Html.Hidden("FieldId", Model.FieldId) %>

并且它们仍然具有“0”作为值,如

<input type="hidden" value="0" name="FieldId" id="FieldId">

如果我刷新页面,我的Action会获取新数据并将值更改为正确的ID。但是,如果我使用RedirectToAction("Unsubscribe"),我将丢失数据并且无法通过ViewData传递成功/错误消息,我必须使用RedirectToAction("Unsubscribe", new { something = msg })而我不希望这样。< / p>

为什么视图会加载原始值而不是模型中新更新的值?

谢谢。

2 个答案:

答案 0 :(得分:1)

问题不在于将修改后的模型传递回视图。这恰好发生了。您的问题与HTML帮助程序的工作方式有关。这是他们的正常行为是设计的。绑定输入字段的值时,它们首先查看POSTed值,然后查看ViewData和视图模型中的值。这意味着您无法修改控制器操作中的POSTed值。作为解决方法:

<input type="hidden" value="<%= Model.FieldId %>" name="FieldId" id="FieldId" />

我有answeredmanybefore并继续回答它,希望人们最终会开始注意到它。

答案 1 :(得分:0)

您可以尝试将其传递给另一个控制器。试试这个,看它是否有效。我创建了一个额外的控制器。您需要创建一个新视图才能使其正常工作

[HttpPost] 
public ActionResult Unsubscribe(UnsubscribeViewModel model) 
{ 
    // let's convert into DalModel 
    UnsubscribeModel m = model.ToUnsubscribeModel(); 

    // let's save into the db 
    myRepository.UpdateUnsubscribe(m); 

    // because I'm using 2 models, let's get the new ID  
    // and append to he View model 
    model.FieldId = m.unsubscribe_id; 

    // let's return the new model to the View 
    return View("UnsubscribeResult", model); 
} 


public ActionResult UnsubscribeResult(UnsubscribeViewModel model) 
{ 
     return View(model); 
} 
相关问题