How does Html.EditorFor process changes to the model

空扰寡人 提交于 2019-12-25 08:16:46

问题


I'm trying to figure out why why and how EditorFor caches information.

This is a simple program that has one two textareas. One for input and one for output. The reason for a text area for output is that it makes a select all copy easier.

My code is pretty simple. First my controller puts some default value

    public ActionResult MoveCss()
    {
        MoveCssIO model = new MoveCssIO(); ;
        model.InputCss = "Fish";
        return View(model);
    }

Then my model kicks in and makes output the uppercase of input

    [Required(ErrorMessage="Please provide some text to transform")]
    [DataType(DataType.MultilineText)]
    public string InputCss { get; set; }


    private string _OutputCss;

    [DataType(DataType.MultilineText)]
    public string OutputCss { 
        get
        {
            Transform();
            return _OutputCss;
        }
        set
        {
            _OutputCss = value;
        }
    }

    private void Transform()
    {
        if (!string.IsNullOrWhiteSpace(InputCss))
        {
            _OutputCss = InputCss.ToUpper();
        }
    }

This goes to my view

##
@Html.Encode(Model.OutputCss)
$$
@Html.DisplayFor(model => model.OutputCss)
&&
@Html.EditorFor(model => model.OutputCss)
%%

So at initial load I get

##
FISH
$$
FISH
&&
<textarea class="text-box multi-line" id="OutputCss" name="OutputCss">
FISH</textarea>
%%

I then use an editor for InputCss (not shown) to change the value on InputCss to ham

    [HttpPost]
    public ActionResult MoveCss(MoveCssIO model)
    {
        return View(model);
    }

This set my OutputCss to HAM and the page does a reload (no ajax) but when I get for output is

##
HAM
$$
HAM
&&
<textarea class="text-box multi-line" id="OutputCss" name="OutputCss">
FISH</textarea>
%%

My question is why is the value in Html.EditorFor different than Html.DisplayFor and how do i fix this?

Updated: To add a bit of clarity


回答1:


Your question is extremely unclear but I suspect that you are trying to modify some value in a POST action and you are still seeing the old value when the view is rendered. If this is the case you need to remove it from the modelstate or html helpers will always bind the old value:

[HttpPost]
public ActionResult MoveCss(MoveCssIO model)
{
    // you are changing a POSTed value here so make sure
    // you remove it from the model state or HTML helpers 
    // will use the original value
    model.InputCss = "ham"; 
    ModelState.Remove("InputCss");
    return View(model);
}

Also note that there is absolutely no caching involved with editor/display templates.



来源:https://stackoverflow.com/questions/5305572/how-does-html-editorfor-process-changes-to-the-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!