Mr. Martin's programming school

Coding MVC

« The Views »
We got a lot per automatics, even if we sometimes get it wrong. But that is how it is. Very few people write a lot of code and get it all right the first time. That is why we call it development. We don't just make it, we develop it. Trial and error, experimenting etc. often called R&D, Research and Development. So, let us do some research.

We will soon se that the root cause for this problem is a naming convention. This version of Visual Studio that I have actually seems to enforce a naming convention, and that differs from mine. Maybe you worked in another version, and did not run into the same problem. Let us first fix the problem before we discuss the naming convention.

We can start with the .../Views/Person/Index.cshtml file. Take a look at the parts that lists the items and makes the links that did not work:



Note that the link parameter data is commented out. The links does not contain any information about what item we wish to edit, delete or see in details view.

To understand the @Html.ActionLink stuff just look at the html code that was generated by it. Use 'View source' or whatever it is called in your browser, or hit F12 for all debugging and other tools, while running your project. This is what it looks like to me when I check one row's links:



So, the scaffolding did not like my Id's. A look into some Microsoft database will reveal that foreign keys by standard are composed by table name, underscore and 'Id'. Then it would be likely that the other end of the foreign key, i.e. the key name in the table that has the key, should be named likewise. In our case 'Persons_Id' and 'Phones_Id' respectively.

I tried that. Changed in the database, removed my view folder and the controller, and generated all from scratch again.

Do that, and to generate all from scratch do this:


Run your program and naviagate to .../Views/Persons view like we did before.



Looks nice. We even got the first name back for some mysterious reason. To be correct, it should be there, but it is a mystery that it was not when the Id was not following standard. Scaffolding probably ignored Id and thought that FirstName was a key, but could not use it. Try the Edit link:



The Details link also works:



And so does the Delete link:



Everything seems to work fine now, you can list, add, edit and delete persons. There is only one problem, you can delete a person that has a phone, which will leave the phone 'hanging' loose in the database. Normally this is fixed in code some way, or by constraints in the database. The latter would cause our program to crash, so we still would need to fix it in code. However, we really do not care about phones without owners, since we later will add a function to assign a pone to a person.