简体   繁体   中英

MVC NotMapped attribute EditorFor returning null value in Edit.cshtml but not Create.cshtml

This question relates to a Visual Studio 2013, Asp.net MVC-5.2.2 project:

I have a NotMapped string attribute in my class:

    [NotMapped]
    public string myNotMappedAttribute{ get; set; }

I use this attribute, which is not mapped in the original table of the Controller, to fill a column in a different table that has a foreign key relationship with the Controller's table under consideration. Again, this idea works perfectly in Create, but not edit.

I have an MVC EditorFor box that works in the Create.cshtml (razor) as follows:

    <div class="editor-label">
        @Html.LabelFor(model => model.myNotMappedAttribute)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.myNotMappedAttribute)
        @Html.ValidationMessageFor(model => model.myNotMappedAttribute)
    </div>

However, the exact same razor code returns null when used in the Edit.cshtml file.

In the Edit post-back method of the controller, this attribute (and only this attribute) is null the other attributes have the correct values. I even moved this attribute so it wouldn't be the last attribute, and one after it was correct.

Any ideas as to why this would work in Create and not Edit?

Turns out that a new default project that I used had some bind attributes in the controller's post-back Edit method:

public ActionResult Edit([Bind(Include = "myAttribute_1,myAttribute_2,myAttribute_3")] MyModel myModel)

One can just omit this and it will work:

[HttpPost]
    public ActionResult Edit(MyModel myModel)

Presumably, adding this attribute to the bind list will also work, though I didn't check that personally myself.

NOTE: I really didn't know the answer to this question, but pondering the mystery, I eventually saw those attributes. I didn't even think the method worth putting in the original question as I was fairly certain that it would be the Razor code that was a problem. Also, I was originally using a dropdown that wasn't working, and decided to replace it with a textbox for simplicity; that turned out to be a wise decision, as one can imagine the number of red-herrings in debugging the textbox!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM