Difference Between UpdateModel And TryUpdateModel Function

Right now, we will do some modification to our existing code.


Move the condition now, which are we doing here. We are checking the condition, when the updatemodel state is invoked. Let’s quickly run our solution and see the output.



Now, we will not fill any data. At the moment, we will click on create button



Now, we are getting this error as the name parameter was not supplied. Remember, we have a stored procedure.

At the moment, if you look at the stored procedure, all the parameters are required



Due to this, we are getting an error name, as a parameter was not supplied. It says that the values are not supplied to null and to make it optional, you have to set to null.



Now, let's run the solution again. Click on create. You will see a row got inserted, which does not contain any detail, as mentioned below.



In SQL, it is shown as follows.



A NULL value got inserted, which means an insert method is executed. Now, we have to make all the fields mandatory because we don’t want it to be a NULL entry.

Now, install Entity Framework in Business layer and write a validation, as shown below.



Now, let’s run the solution and click on create.


We are getting this error notice, where we are getting this exception. We got this exception when UpdateModel is invoked. Instead of using UpdateModel, we will use TryUpdate model and see what is going to happen. 

0
We had used TryUpdateModel. Now, let’s run the app and click create.



As you can see from the screenshot, shown above, we are getting a validation error.

NOTE

  • UpdateModel() throws an exception, if validation fails, whereas TryUpdateModel() will never throw an exception.
  • The similarity between both is that the functions are used to update the model with the form values and perform the validations.

Is it mandatory to use UpdateModel() or TryUpdateModel() function to update the model? No, it is not.

Up Next
    Ebook Download
    View all
    Learn
    View all