Click here to Skip to main content
15,884,986 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,

I am coding a new project which is something like blog. Simply, there is a post and a comment section. I am adding comment by posting the page. And this 'refresh' the page.

That is not good for the users. No need to refresh the page.

I am good at Mvc and C#. However, I have a little knowledge on Ajax and JS.

I made research and did some stuff. However, it does not work at all. Let me represent.

In View;

HTML
<section class="panel-footer pb0">
                                     <script type="text/javascript">
                                         $("#commentCreate").click(function (e) {
                                             e.preventDefault();
                                             alert("Here");
                                             var comment = getComment();
                                             Console.dir(comment);

                                             if (comment == null) {
                                                 alert("Specify a name please!");
                                                 return;
                                             }

                                             var json = JSON.stringify(comment);
                                             function getComment() {
                                                 var commentText = $("#CommentText").val();
                                                 var nameSurname = $("#NameSurname").val();
                                                 var email = $("#EMail").val();

                                                 return (namesurname == "") ? null : { CommentText: commentText, NameSurname: namesurname, EMail: email };

                                             $.ajax({
                                                 url: '/Blog/Comment',
                                                 type: 'POST',
                                                 dataType: 'json',
                                                 data: json,
                                                 contentType: 'application/json; charset=utf-8',
                                                 success: function (data) {
                                                     console.log(data);
                                                     $.each(data, function (i, obj) {
                                                         $("#resultMessage").html(obj.CommentText);
                                                     });
                                                 }
                                             });                                              }

                                         });
    </script>
                                <h4 class="mt0 mb15 text-primary">Yorum Yap</h4>
                             

                                <form id="deneme"  class="form-horizontal" method="post"  >
                                 
                                    <div class="form-group">
                                        <label class="col-sm-3 control-label">Name <span class="text-danger">*</span></label>
                                        <div class="col-sm-9">
                                            <input type="text" name="Name" id="Name" class="form-control" >
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-sm-3 control-label">Email <span class="text-danger">*</span></label>
                                        <div class="col-sm-9">
                                            <input type="text" name="EMail" id="EMail" class="form-control" >
                                        </div>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label class="col-sm-3 control-label">Comment</label>
                                        <div class="col-sm-9">
                                            <textarea class="form-control" rows="6" id="CommentText" name="CommentText"></textarea>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <div class="col-sm-12">
                                            <button type="reset" class="btn btn-default">Reset</button>
                                            <button type="submit" class="btn btn-success" id="commentCreate" onclick="commentCreate()" ><span class="ladda-label">Comment</span></button>
                                        </div>
                                    </div>
                                </form>
                            </section>


In Controller

C#
[HttpPost]
      public ActionResult Comment(Comment inputModel)
      {
          if (ModelState.IsValid)
          {
             //Insert To DB
              return Json(new Comment { CommentText = "Smthng???" });
          }
          else
          {
              string errorMessage = "<div class=\"validation-summary-errors\">The following errors occurred:<ul>";
              foreach (var key in ModelState.Keys)
              {
                  var error = ModelState[key].Errors.FirstOrDefault();
                  if (error != null)
                  {
                      errorMessage += "<li class=\"field-validation-error\">" + error.ErrorMessage + "</li>";
                  }
              }
              errorMessage += "</ul>";
              return Json(new Comment { CommentText = errorMessage });
          }
      }


What is wrong with my code? What should I do? The thing that I am trying to do, is so simple but, if you don' t have enough knowledge; it becomes the most difficult thing all over the world.

Thank you.
Posted
Updated 15-Sep-15 22:29pm
v2

I tidied up the code a bit, there was nothing majorly wrong, just case issues, issues with code formatting not being valid etc. Basic debugging such as using the browser's console to check for errors and dev tools in general will have highlighted these issues.

XML
<section class="panel-footer pb0">
    <h4 class="mt0 mb15 text-primary">Yorum Yap</h4>

    <form id="deneme" class="form-horizontal" method="post">

        <div class="form-group">
            <label class="col-sm-3 control-label">Name <span class="text-danger">*</span></label>
            <div class="col-sm-9">
                <input type="text" name="Name" id="Name" class="form-control">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">Email <span class="text-danger">*</span></label>
            <div class="col-sm-9">
                <input type="text" name="EMail" id="EMail" class="form-control">
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label">Comment</label>
            <div class="col-sm-9">
                <textarea class="form-control" rows="6" id="CommentText" name="CommentText"></textarea>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-12">
                <button type="reset" class="btn btn-default">Reset</button>
                <button type="submit" class="btn btn-success" id="commentCreate" ><span class="ladda-label">Comment</span></button>
            </div>
        </div>
    </form>
</section>
<script type="text/javascript">
    $("#commentCreate").click(function (e) {
        e.preventDefault();

        var commentText = $("#CommentText").val();
        // this element doesn't exist in your markup so I'm using "Name" instead
        //var nameSurname = $("#NameSurname").val();
        var nameSurname = $("#Name").val();
        var email = $("#EMail").val();

        // you were using nameSurname and namesurname, js is case-sensitive
        var comment = (nameSurname == "") ? null : { CommentText: commentText, NameSurname: nameSurname, EMail: email };

        if (comment == null) {
            alert("Specify a name please!");
            return;
        }

        var json = JSON.stringify(comment);

        $.ajax({
            url: '/Blog/Comment',
            type: 'POST',
            dataType: 'json',
            data: json,
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                console.log(data);
                // resultMessage doesn't exist so I've changed this to an alert
                // I also ditched the loop as you only return one object
                //$("#resultMessage").html(obj.CommentText);
                alert(data.CommentText);
            }
        });
    }); // your js wasn't valid here, you didn't have the right closing braces
</script>
 
Share this answer
 
Comments
FoxRoot 16-Sep-15 6:17am    
Thank you for your interest. Now it does not do anything even refresh. Does not show anything on chrome console. What am I missing?
FoxRoot 16-Sep-15 6:24am    
Thank you! I typed console.dir(comment); now it is full. However, it does not hit to controller action. What am I missing? I think Ajax part of code does not work :/
F-ES Sitecore 16-Sep-15 6:36am    
Well the above works for me. Use the network tab of your browser tools to examine the call that is made to see if one is made at all, and if so what the result is. Error messages are normally hidden inside the response, which you can view from the dev tools.
FoxRoot 16-Sep-15 6:40am    
There is a Comment page and it's status is Ok: Status Code:200 OK


I am going crazy. What is wrong :(
F-ES Sitecore 16-Sep-15 6:45am    
That means it worked, if you examine the response you should see what was sent back which should look like json. Check the success event fires and what is sent back matches what is what you're accessing in the success event.
I have changed in Javascript code. See below code:
JavaScript
$("#personCreate").click(function () {
	var comment= getComment();

	if (person == null) {
	   alert("Specify a name please!");
	   return;
	}

	var json = JSON.stringify(comment);

	$.ajax({
	   url: '/Blog/Comment',
	   type: 'POST',
	   dataType: 'json',
	   data: json,
	   contentType: 'application/json; charset=utf-8',
	   success: function (data) {
		// What should I do here?		
		$.each(data, function (i, obj) {
			$("#resultMessage").html(obj.CommentText);
		});
	   }
	});
});
 
Share this answer
 
Comments
FoxRoot 16-Sep-15 3:46am    
Thank you so much. But I am getting 'Uncaught TypeError: Cannot read property 'validate' of undefined'. As I got before.
[no name] 16-Sep-15 3:50am    
Is that hitting your controller action?
FoxRoot 16-Sep-15 3:52am    
I resolved Uncaught type error. But it does not hit controller action. Just refresh the page.
F-ES Sitecore 16-Sep-15 4:17am    
$("#personCreate").click(function (e) {
e.preventDefault();
// rest of code here
FoxRoot 16-Sep-15 4:19am    
Thank you. Stil just refreshs the page.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900