0

When I want to add a comment to my database I get the following error(The order is the same as in the database) :

System.Data.SqlClient.SqlException was unhandled by user code
  Class=16
  ErrorCode=-2146232060
  HResult=-2146232060
  LineNumber=0
  Message=The parameterized query '(@UserId nvarchar(36),@TimeStamp datetime,@CategoryId int,@PostI' expects the parameter '@Comment', which was not supplied.
  Number=8178
  Procedure=""
  Server=MAXIM-HP\DATAMANAGEMENT
  Source=.Net SqlClient Data Provider
  State=1
  StackTrace:
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
       at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
       at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
       at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
       at BlogMaxim.Repositories.CommentRepository.Add(Comments comment) in C:\nmct\2e Jaar\1e sem\project\BlogMaxim\BlogMaxim\Repositories\CommentRepository.cs:line 98
       at BlogMaxim.Controllers.CommentController.AddComment(Comments comment) in C:\nmct\2e Jaar\1e sem\project\BlogMaxim\BlogMaxim\Controllers\CommentController.cs:line 43
       at lambda_method(Closure , ControllerBase , Object[] )
       at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
       at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
       at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
       at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
  InnerException: 

This is my method where I add the items into the database.

Add comments method

This is were I make the Comments object:

namespace BlogMaxim.Models {
    public class Comments
    {
        public int Id { get; set; }
         public int CategoryId { get; set; }
         public int PostId { get; set; }
        public string Comment { get; set; }
         public string UserId { get; set; }
         public DateTime Timestamp { get; set; }
    } }

This is my form:

@model IEnumerable<BlogMaxim.Models.Comments>

@if (User.Identity.IsAuthenticated)
{
    <form method="post" action="/comment/addcomment">
        <label>Vul hier commentaar in: </label>
        <input type="hidden" width="150" name="PostId" value="@ViewBag.pId" />
        <input type="text" width="150" name="Comment" />
        <input type="submit" width="150" value="Toevoegen" />

    </form>
Maxim
  • 631
  • 5
  • 10

1 Answers1

0

You are getting a NULL value in the Comment property of your comment object.

When looking at your form markup, It looks like your comment input field has a different name(Description) than what you have in your viewmodel. For MVC Model binding to work properly, Your input field name should match with your model/view model property name.

Change the name attribute value of the comment textbox to "Comment" and it should work.

<form method="post" action="/comment/addcomment">      
   <input type="text" name="Comment" />
   <input type="hidden" name="PostId" value="@ViewBag.pId" />
   <input type="submit" />
</form>

Going further, Whenever you get such errors, You should try to put a breakpoints in your code and try to debug and see what values your variables are having. This will help you fix a lot of issues by yourself.

Also, another thing i noticed is, you are using comment.CategoryId, but in your form, you do not have any input field to set the value of the CategoryId. Unless it is a NULLABLE field in your db, you should be passing that value also from your view/set that value to your comment object before saving the comment.

If you want to set to view

<form method="post" action="/comment/addcomment">      
   <input type="text" name="Comment" />
   <input type="hidden" name="PostId" value="@ViewBag.pId" />
   <input type="hidden" name="CategoryId" value="1" />
   <input type="hidden" value="@ViewBag.pId" />
   <input type="submit" />
</form>

I hard coded the value for CategoryId as 1 in the form. You may read it from somewhere and set it.

Also, you are using comment.UserId. So make sure you set that value also before running your save code.

Shyju
  • 214,206
  • 104
  • 411
  • 497
  • I have did that, I'ved added my form to the post above. – Maxim Dec 29 '15 at 14:23
  • I changed it, and I now get a An exception of type 'System.NullReferenceException' occurred in BlogMaxim.dll but was not handled in user code Additional information: Object reference not set to an instance of an object. – Maxim Dec 29 '15 at 14:27
  • You are missing other property values. See my updated answer. – Shyju Dec 29 '15 at 14:34
  • The CategoryId in my Comments has been deleted cause I don't even know why and how I should use this (it's pointless). I don't quite understand what you mean by 'setting that value' for the comment.UserId – Maxim Dec 29 '15 at 14:52
  • Your save code is using both UserId and CategoryId. So you should set those properties of your comment object before executing the save code. UserId will be the current logged in user's Id i guess. You should know what categoryId you want to save against. You can leave it as as it is(NULL) If your db column allows null values for CategoryId column. – Shyju Dec 29 '15 at 14:53