简体   繁体   中英

my model binding is working even If I didn't show it in html

I have a form that can be reached by different ways. In the URL, if user comes with ?data=johndoe (example), I didn't want to deal with another property, so I didn't show it to user and I don't care of this property. Because I use the same form and the same Controller when user submit the form, I just want to receive that other property to null in controller ands then treat it differently.

So

I have a model that I init and return to a form,

public class MyModel
{
public int selectedValue {get;set;}
public string data {get;set;}

public MyModel(){
this.selectedValue = 5;
}
}

public ActionResult Index(){
MyModel model = new MyModel(){};
Return View(model);
}

On the view, I decided to not show the selectedValue in order to receive it as null value when user submit the form, so in the form I just

@Html.EditorFor(m => m.data)

And nothing for the selectedValue.

Then In the controller

[HttpPost]
public ActionResult Index(MyModel model)
{
// here I get model.selectedValue = 5, WHY?
}

I want to get model.selectedValue at null If I didn't use it in the form, it looks normal, no?

If it's normal, why and How can I fix this issue from the razor page? Any clean idea on how Can I do this?

Thanks in advance

You get 5 because you set it in the constructor

public MyModel(){
    // comment this line to get rid of 5
    // this.selectedValue = 5;  
}

You also won't get it set to null , because you use int which is a value type that doesn't have null as value. You can use nullable int int? or some default value, like -1 to indicate there was no selection.

It's not passed from the form, but a new instance of MyModel is still generated, and, right there in your constructor, you're setting the value to 5.

public class MyModel
{
    public int selectedValue {get;set;}
    public string data {get;set;}

    public MyModel() {
        // MyModel.selectedValue will always be 5 unless specified otherwise
        this.selectedValue = 5;
    }
}

I want to get model.selectedValue at null

in which case, change your model to:

public class MyModel
{
    public int? selectedValue {get;set;}
    public string data {get;set;}
}

if you can't change the Model (eg third-party) then you'll have to provide a value in the view "fix this issue in the razor view". You could set it to zero or some other magic-number (use a constant...) to indicate a default value.

You initialized the variable selectedValue in the constructor.

When model binding creates the instance, this constructor is also called, which means the variable selectedValue in the Index action method is equal to 5.

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