Can the ViewBag name be the same as the Model property name in a DropDownList?










11















I am working on an ASP.NET MVC-4 web application. I'm defining the following inside my action method to build a SelectList:



ViewBag.CustomerID = new SelectList(db.CustomerSyncs, "CustomerID", "Name");


Then I am rendering my DropDownListFor as follow inside my View:



 @Html.DropDownListFor(model => model.CustomerID, (SelectList)ViewBag.CustomerID, "please select")


As shown I am naming the ViewBag property to be equal to the Model property name which is CustomerID. From my own testing, defining the same name didn't cause any problem or conflict but should I avoid this ?










share|improve this question



















  • 1





    Do not do this - it does cause problems (for example you cannot get any client side validation)

    – user3559349
    May 11 '16 at 11:26






  • 2





    @StephenMuecke why i will not get any client side validation .... now i have the customerID as int and it is required. and by default i got a client side validation , that when a user try to submit a form he will get an error that the CustomerID is required... so not sure what do you mean by i cannot get any client side validation ...

    – john Gu
    May 11 '16 at 11:31






  • 1





    Another issue is that if the value of CustomerID is set in the controller (i.e. editing and existing entity), it will not selected correctly in the dropdownlist.

    – user3559349
    May 11 '16 at 11:31






  • 1





    @StephenMuecke retruning back to the client validation .. now the value for the "please select" will be null,, so the client side validation will still work .. here is the markup <select data-val="true" data-val-number="The field CustomerID must be a number." data-val-required="The CustomerID field is required." id="CustomerID" name="CustomerID"><option value="">please select</option> <option value="1">CustomerA</option>

    – john Gu
    May 11 '16 at 11:34






  • 2





    @SeM, Absolutely not. You will not get client side validation.

    – user3559349
    May 11 '16 at 11:56















11















I am working on an ASP.NET MVC-4 web application. I'm defining the following inside my action method to build a SelectList:



ViewBag.CustomerID = new SelectList(db.CustomerSyncs, "CustomerID", "Name");


Then I am rendering my DropDownListFor as follow inside my View:



 @Html.DropDownListFor(model => model.CustomerID, (SelectList)ViewBag.CustomerID, "please select")


As shown I am naming the ViewBag property to be equal to the Model property name which is CustomerID. From my own testing, defining the same name didn't cause any problem or conflict but should I avoid this ?










share|improve this question



















  • 1





    Do not do this - it does cause problems (for example you cannot get any client side validation)

    – user3559349
    May 11 '16 at 11:26






  • 2





    @StephenMuecke why i will not get any client side validation .... now i have the customerID as int and it is required. and by default i got a client side validation , that when a user try to submit a form he will get an error that the CustomerID is required... so not sure what do you mean by i cannot get any client side validation ...

    – john Gu
    May 11 '16 at 11:31






  • 1





    Another issue is that if the value of CustomerID is set in the controller (i.e. editing and existing entity), it will not selected correctly in the dropdownlist.

    – user3559349
    May 11 '16 at 11:31






  • 1





    @StephenMuecke retruning back to the client validation .. now the value for the "please select" will be null,, so the client side validation will still work .. here is the markup <select data-val="true" data-val-number="The field CustomerID must be a number." data-val-required="The CustomerID field is required." id="CustomerID" name="CustomerID"><option value="">please select</option> <option value="1">CustomerA</option>

    – john Gu
    May 11 '16 at 11:34






  • 2





    @SeM, Absolutely not. You will not get client side validation.

    – user3559349
    May 11 '16 at 11:56













11












11








11


2






I am working on an ASP.NET MVC-4 web application. I'm defining the following inside my action method to build a SelectList:



ViewBag.CustomerID = new SelectList(db.CustomerSyncs, "CustomerID", "Name");


Then I am rendering my DropDownListFor as follow inside my View:



 @Html.DropDownListFor(model => model.CustomerID, (SelectList)ViewBag.CustomerID, "please select")


As shown I am naming the ViewBag property to be equal to the Model property name which is CustomerID. From my own testing, defining the same name didn't cause any problem or conflict but should I avoid this ?










share|improve this question
















I am working on an ASP.NET MVC-4 web application. I'm defining the following inside my action method to build a SelectList:



ViewBag.CustomerID = new SelectList(db.CustomerSyncs, "CustomerID", "Name");


Then I am rendering my DropDownListFor as follow inside my View:



 @Html.DropDownListFor(model => model.CustomerID, (SelectList)ViewBag.CustomerID, "please select")


As shown I am naming the ViewBag property to be equal to the Model property name which is CustomerID. From my own testing, defining the same name didn't cause any problem or conflict but should I avoid this ?







asp.net asp.net-mvc asp.net-mvc-4 html-helper html.dropdownlistfor






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 2 '17 at 17:06









Winter

1,87651538




1,87651538










asked May 11 '16 at 11:25









john Gujohn Gu

1,53842150320




1,53842150320







  • 1





    Do not do this - it does cause problems (for example you cannot get any client side validation)

    – user3559349
    May 11 '16 at 11:26






  • 2





    @StephenMuecke why i will not get any client side validation .... now i have the customerID as int and it is required. and by default i got a client side validation , that when a user try to submit a form he will get an error that the CustomerID is required... so not sure what do you mean by i cannot get any client side validation ...

    – john Gu
    May 11 '16 at 11:31






  • 1





    Another issue is that if the value of CustomerID is set in the controller (i.e. editing and existing entity), it will not selected correctly in the dropdownlist.

    – user3559349
    May 11 '16 at 11:31






  • 1





    @StephenMuecke retruning back to the client validation .. now the value for the "please select" will be null,, so the client side validation will still work .. here is the markup <select data-val="true" data-val-number="The field CustomerID must be a number." data-val-required="The CustomerID field is required." id="CustomerID" name="CustomerID"><option value="">please select</option> <option value="1">CustomerA</option>

    – john Gu
    May 11 '16 at 11:34






  • 2





    @SeM, Absolutely not. You will not get client side validation.

    – user3559349
    May 11 '16 at 11:56












  • 1





    Do not do this - it does cause problems (for example you cannot get any client side validation)

    – user3559349
    May 11 '16 at 11:26






  • 2





    @StephenMuecke why i will not get any client side validation .... now i have the customerID as int and it is required. and by default i got a client side validation , that when a user try to submit a form he will get an error that the CustomerID is required... so not sure what do you mean by i cannot get any client side validation ...

    – john Gu
    May 11 '16 at 11:31






  • 1





    Another issue is that if the value of CustomerID is set in the controller (i.e. editing and existing entity), it will not selected correctly in the dropdownlist.

    – user3559349
    May 11 '16 at 11:31






  • 1





    @StephenMuecke retruning back to the client validation .. now the value for the "please select" will be null,, so the client side validation will still work .. here is the markup <select data-val="true" data-val-number="The field CustomerID must be a number." data-val-required="The CustomerID field is required." id="CustomerID" name="CustomerID"><option value="">please select</option> <option value="1">CustomerA</option>

    – john Gu
    May 11 '16 at 11:34






  • 2





    @SeM, Absolutely not. You will not get client side validation.

    – user3559349
    May 11 '16 at 11:56







1




1





Do not do this - it does cause problems (for example you cannot get any client side validation)

– user3559349
May 11 '16 at 11:26





Do not do this - it does cause problems (for example you cannot get any client side validation)

– user3559349
May 11 '16 at 11:26




2




2





@StephenMuecke why i will not get any client side validation .... now i have the customerID as int and it is required. and by default i got a client side validation , that when a user try to submit a form he will get an error that the CustomerID is required... so not sure what do you mean by i cannot get any client side validation ...

– john Gu
May 11 '16 at 11:31





@StephenMuecke why i will not get any client side validation .... now i have the customerID as int and it is required. and by default i got a client side validation , that when a user try to submit a form he will get an error that the CustomerID is required... so not sure what do you mean by i cannot get any client side validation ...

– john Gu
May 11 '16 at 11:31




1




1





Another issue is that if the value of CustomerID is set in the controller (i.e. editing and existing entity), it will not selected correctly in the dropdownlist.

– user3559349
May 11 '16 at 11:31





Another issue is that if the value of CustomerID is set in the controller (i.e. editing and existing entity), it will not selected correctly in the dropdownlist.

– user3559349
May 11 '16 at 11:31




1




1





@StephenMuecke retruning back to the client validation .. now the value for the "please select" will be null,, so the client side validation will still work .. here is the markup <select data-val="true" data-val-number="The field CustomerID must be a number." data-val-required="The CustomerID field is required." id="CustomerID" name="CustomerID"><option value="">please select</option> <option value="1">CustomerA</option>

– john Gu
May 11 '16 at 11:34





@StephenMuecke retruning back to the client validation .. now the value for the "please select" will be null,, so the client side validation will still work .. here is the markup <select data-val="true" data-val-number="The field CustomerID must be a number." data-val-required="The CustomerID field is required." id="CustomerID" name="CustomerID"><option value="">please select</option> <option value="1">CustomerA</option>

– john Gu
May 11 '16 at 11:34




2




2





@SeM, Absolutely not. You will not get client side validation.

– user3559349
May 11 '16 at 11:56





@SeM, Absolutely not. You will not get client side validation.

– user3559349
May 11 '16 at 11:56












2 Answers
2






active

oldest

votes


















13














You should not use the same name for the model property and the ViewBag property (and ideally you should not be using ViewBag at all, but rather a view model with a IEnumerable<SelectListItem> property).



When using @Html.DropDownListFor(m => m.CustomerId, ....) the first "Please Select" option will always be selected even if the value of the model property has been set and matches one of the options. The reason is that the method first generates a new IEnumerable<SelectListItem> based on the one you have supplied in order to set the value of the Selected property. In order to set the Selected property, it reads the value of CustomerID from ViewData, and the first one it finds is "IEnumerable<SelectListItem>" (not the value of the model property) and cannot match that string with any of your options, so the first option is selected (because something has to be).



When using @Html.DropDownList("CustomerId", ....), no data-val-* attributes will be generated and you will not get any client side validation



Refer this DotNetFiddle showing a comparison of possible use cases. Only by using different names for the model property and the ViewBag property will it all work correctly.






share|improve this answer























  • ok, you right everywhere

    – teo van kot
    May 11 '16 at 13:35











  • Error in fiddle , when i click on submit button . It says "The ViewData item that has the key 'CustomerA' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'. "

    – Saurabh
    Jul 24 '17 at 8:12











  • @Saurabh, That's because I did not repopulate the SelectLists in the POST method before returning the view (as per the GET method) - but that is not the point of the fiddle - its to show that you cannot get correct 2-way binding and/or validation if the same name is used for property your binding to and the SelectList (and if you want more details on that error - refer this question/answer

    – user3559349
    Jul 24 '17 at 8:16


















1














There is not harm to use it. You will not get any error. but best practice is to bind model property.






share|improve this answer























  • @US3-57384 can you adivce more ?

    – john Gu
    May 11 '16 at 11:36











  • See what i use in my code. which solve your issue and works fine. (IEnumerable<SelectListItem>)ViewBag.RT

    – CrazyDev
    May 11 '16 at 11:42











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37161202%2fcan-the-viewbag-name-be-the-same-as-the-model-property-name-in-a-dropdownlist%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









13














You should not use the same name for the model property and the ViewBag property (and ideally you should not be using ViewBag at all, but rather a view model with a IEnumerable<SelectListItem> property).



When using @Html.DropDownListFor(m => m.CustomerId, ....) the first "Please Select" option will always be selected even if the value of the model property has been set and matches one of the options. The reason is that the method first generates a new IEnumerable<SelectListItem> based on the one you have supplied in order to set the value of the Selected property. In order to set the Selected property, it reads the value of CustomerID from ViewData, and the first one it finds is "IEnumerable<SelectListItem>" (not the value of the model property) and cannot match that string with any of your options, so the first option is selected (because something has to be).



When using @Html.DropDownList("CustomerId", ....), no data-val-* attributes will be generated and you will not get any client side validation



Refer this DotNetFiddle showing a comparison of possible use cases. Only by using different names for the model property and the ViewBag property will it all work correctly.






share|improve this answer























  • ok, you right everywhere

    – teo van kot
    May 11 '16 at 13:35











  • Error in fiddle , when i click on submit button . It says "The ViewData item that has the key 'CustomerA' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'. "

    – Saurabh
    Jul 24 '17 at 8:12











  • @Saurabh, That's because I did not repopulate the SelectLists in the POST method before returning the view (as per the GET method) - but that is not the point of the fiddle - its to show that you cannot get correct 2-way binding and/or validation if the same name is used for property your binding to and the SelectList (and if you want more details on that error - refer this question/answer

    – user3559349
    Jul 24 '17 at 8:16















13














You should not use the same name for the model property and the ViewBag property (and ideally you should not be using ViewBag at all, but rather a view model with a IEnumerable<SelectListItem> property).



When using @Html.DropDownListFor(m => m.CustomerId, ....) the first "Please Select" option will always be selected even if the value of the model property has been set and matches one of the options. The reason is that the method first generates a new IEnumerable<SelectListItem> based on the one you have supplied in order to set the value of the Selected property. In order to set the Selected property, it reads the value of CustomerID from ViewData, and the first one it finds is "IEnumerable<SelectListItem>" (not the value of the model property) and cannot match that string with any of your options, so the first option is selected (because something has to be).



When using @Html.DropDownList("CustomerId", ....), no data-val-* attributes will be generated and you will not get any client side validation



Refer this DotNetFiddle showing a comparison of possible use cases. Only by using different names for the model property and the ViewBag property will it all work correctly.






share|improve this answer























  • ok, you right everywhere

    – teo van kot
    May 11 '16 at 13:35











  • Error in fiddle , when i click on submit button . It says "The ViewData item that has the key 'CustomerA' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'. "

    – Saurabh
    Jul 24 '17 at 8:12











  • @Saurabh, That's because I did not repopulate the SelectLists in the POST method before returning the view (as per the GET method) - but that is not the point of the fiddle - its to show that you cannot get correct 2-way binding and/or validation if the same name is used for property your binding to and the SelectList (and if you want more details on that error - refer this question/answer

    – user3559349
    Jul 24 '17 at 8:16













13












13








13







You should not use the same name for the model property and the ViewBag property (and ideally you should not be using ViewBag at all, but rather a view model with a IEnumerable<SelectListItem> property).



When using @Html.DropDownListFor(m => m.CustomerId, ....) the first "Please Select" option will always be selected even if the value of the model property has been set and matches one of the options. The reason is that the method first generates a new IEnumerable<SelectListItem> based on the one you have supplied in order to set the value of the Selected property. In order to set the Selected property, it reads the value of CustomerID from ViewData, and the first one it finds is "IEnumerable<SelectListItem>" (not the value of the model property) and cannot match that string with any of your options, so the first option is selected (because something has to be).



When using @Html.DropDownList("CustomerId", ....), no data-val-* attributes will be generated and you will not get any client side validation



Refer this DotNetFiddle showing a comparison of possible use cases. Only by using different names for the model property and the ViewBag property will it all work correctly.






share|improve this answer













You should not use the same name for the model property and the ViewBag property (and ideally you should not be using ViewBag at all, but rather a view model with a IEnumerable<SelectListItem> property).



When using @Html.DropDownListFor(m => m.CustomerId, ....) the first "Please Select" option will always be selected even if the value of the model property has been set and matches one of the options. The reason is that the method first generates a new IEnumerable<SelectListItem> based on the one you have supplied in order to set the value of the Selected property. In order to set the Selected property, it reads the value of CustomerID from ViewData, and the first one it finds is "IEnumerable<SelectListItem>" (not the value of the model property) and cannot match that string with any of your options, so the first option is selected (because something has to be).



When using @Html.DropDownList("CustomerId", ....), no data-val-* attributes will be generated and you will not get any client side validation



Refer this DotNetFiddle showing a comparison of possible use cases. Only by using different names for the model property and the ViewBag property will it all work correctly.







share|improve this answer












share|improve this answer



share|improve this answer










answered May 11 '16 at 12:21







user3559349



















  • ok, you right everywhere

    – teo van kot
    May 11 '16 at 13:35











  • Error in fiddle , when i click on submit button . It says "The ViewData item that has the key 'CustomerA' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'. "

    – Saurabh
    Jul 24 '17 at 8:12











  • @Saurabh, That's because I did not repopulate the SelectLists in the POST method before returning the view (as per the GET method) - but that is not the point of the fiddle - its to show that you cannot get correct 2-way binding and/or validation if the same name is used for property your binding to and the SelectList (and if you want more details on that error - refer this question/answer

    – user3559349
    Jul 24 '17 at 8:16

















  • ok, you right everywhere

    – teo van kot
    May 11 '16 at 13:35











  • Error in fiddle , when i click on submit button . It says "The ViewData item that has the key 'CustomerA' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'. "

    – Saurabh
    Jul 24 '17 at 8:12











  • @Saurabh, That's because I did not repopulate the SelectLists in the POST method before returning the view (as per the GET method) - but that is not the point of the fiddle - its to show that you cannot get correct 2-way binding and/or validation if the same name is used for property your binding to and the SelectList (and if you want more details on that error - refer this question/answer

    – user3559349
    Jul 24 '17 at 8:16
















ok, you right everywhere

– teo van kot
May 11 '16 at 13:35





ok, you right everywhere

– teo van kot
May 11 '16 at 13:35













Error in fiddle , when i click on submit button . It says "The ViewData item that has the key 'CustomerA' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'. "

– Saurabh
Jul 24 '17 at 8:12





Error in fiddle , when i click on submit button . It says "The ViewData item that has the key 'CustomerA' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'. "

– Saurabh
Jul 24 '17 at 8:12













@Saurabh, That's because I did not repopulate the SelectLists in the POST method before returning the view (as per the GET method) - but that is not the point of the fiddle - its to show that you cannot get correct 2-way binding and/or validation if the same name is used for property your binding to and the SelectList (and if you want more details on that error - refer this question/answer

– user3559349
Jul 24 '17 at 8:16





@Saurabh, That's because I did not repopulate the SelectLists in the POST method before returning the view (as per the GET method) - but that is not the point of the fiddle - its to show that you cannot get correct 2-way binding and/or validation if the same name is used for property your binding to and the SelectList (and if you want more details on that error - refer this question/answer

– user3559349
Jul 24 '17 at 8:16













1














There is not harm to use it. You will not get any error. but best practice is to bind model property.






share|improve this answer























  • @US3-57384 can you adivce more ?

    – john Gu
    May 11 '16 at 11:36











  • See what i use in my code. which solve your issue and works fine. (IEnumerable<SelectListItem>)ViewBag.RT

    – CrazyDev
    May 11 '16 at 11:42
















1














There is not harm to use it. You will not get any error. but best practice is to bind model property.






share|improve this answer























  • @US3-57384 can you adivce more ?

    – john Gu
    May 11 '16 at 11:36











  • See what i use in my code. which solve your issue and works fine. (IEnumerable<SelectListItem>)ViewBag.RT

    – CrazyDev
    May 11 '16 at 11:42














1












1








1







There is not harm to use it. You will not get any error. but best practice is to bind model property.






share|improve this answer













There is not harm to use it. You will not get any error. but best practice is to bind model property.







share|improve this answer












share|improve this answer



share|improve this answer










answered May 11 '16 at 11:35









CrazyDevCrazyDev

11219




11219












  • @US3-57384 can you adivce more ?

    – john Gu
    May 11 '16 at 11:36











  • See what i use in my code. which solve your issue and works fine. (IEnumerable<SelectListItem>)ViewBag.RT

    – CrazyDev
    May 11 '16 at 11:42


















  • @US3-57384 can you adivce more ?

    – john Gu
    May 11 '16 at 11:36











  • See what i use in my code. which solve your issue and works fine. (IEnumerable<SelectListItem>)ViewBag.RT

    – CrazyDev
    May 11 '16 at 11:42

















@US3-57384 can you adivce more ?

– john Gu
May 11 '16 at 11:36





@US3-57384 can you adivce more ?

– john Gu
May 11 '16 at 11:36













See what i use in my code. which solve your issue and works fine. (IEnumerable<SelectListItem>)ViewBag.RT

– CrazyDev
May 11 '16 at 11:42






See what i use in my code. which solve your issue and works fine. (IEnumerable<SelectListItem>)ViewBag.RT

– CrazyDev
May 11 '16 at 11:42


















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37161202%2fcan-the-viewbag-name-be-the-same-as-the-model-property-name-in-a-dropdownlist%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

What does pagestruct do in Eviews?

Dutch intervention in Lombok and Karangasem

Channel Islands