0

i want to send my data from view to controller using ajax but I can't send the data to controller.

Thanks for your help.

That's my View code,

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>SignUp</title>
    <link href="../../css/bootstrap.min.css" rel="stylesheet">
    <link href="../../css/signin.css" rel="stylesheet">
    <script type="text/javascript" src="../../js/jquery-1.11.0.min.js"></script>    
    <script type="text/javascript">

        $(document).on("click", "#btnSignUp", function () {

            var tcNo = document.getElementById('inputTcn').value;
            var nameSurname = document.getElementById("Name").value;
            var eMail = document.getElementById('Email').value;
            var number = document.getElementById("PhoneNumber").value;
            var secretQuestionAnswer = document.getElementById("inputSecretQuestionAnswer").value;
            var password = document.getElementById('inputPassword').value;
            var passwordVerify = document.getElementById("passwordVerify").value;
            //var stateValue = document.getElementById("viewStates").value;

            $.ajax({
                type: 'POST',
                url: '/Home/SignUp',
                dataType: 'json',
                data: {
                    'tcNo': tcNo,
                    'nameSurname': nameSurname,
                    'eMail': eMail,
                    'number': number,
                    'secretQuestionAnswer': secretQuestionAnswer,
                    'password': password,
                    'passwordVerify': passwordVerify,
                    'stateValue': stateValue
                },
                success: function (msg) {
                    alert("bsg");
                },
                error: function (msg) {
                    alert("2");
                }
            });

        });
    </script>
</head>
<body>
    <div class="container">
        <form class="form-signin">

            <h2 class="form-signin-heading"></h2>
            <input id="inputTcn" class="form-control" placeholder="T.C. NO GİRİNİZ" required="" autofocus="">
            <input id="Name" class="form-control" placeholder="ADINIZI SOYADINIZI GİRİNİZ" required="">
            <input id="Email" class="form-control" placeholder="E-MAIL GİRİNİZ" required="">
            <input id="PhoneNumber" class="form-control" placeholder="GSM NUMARANIZI GİRİNİZ" required="">
            <input id="inputSecretQuestionAnswer" class="form-control" placeholder="ÖZEL SORUNUZUN CEVABINI GİRİN">
            <input type="password" id="inputPassword" class="form-control" placeholder="ŞİFRENİZİ GİRİNİZ" required="">
            <input type="password" id="passwordVerify" class="form-control" placeholder="ŞİFRENİZİ TEKRAR GİRİNİZ" required="">
            @Html.DropDownList("viewStates")

            <a id="btnSignUp" class="btn btn-lg btn-primary btn-block btn-danger">KAYIT OL</a>

        </form>
    </div>
</body>
</html>

and here that's my Controller,

 [HttpPost]
        public ActionResult SignUp(string tcNo, string nameSurname, string eMail, string number, 
            string secretQuestionAnswer, string password, string passwordVerify, string stateValue)
        {

            return View();
        }

and I add data to my Dropdownlist at here,

[HttpGet]
        public ActionResult SignUp()
        {
            var database = new KargoDB();
            List<SelectListItem> stateList = (from s in database.States
                select new SelectListItem
                {
                    Text = s.Description,
                    Value = (s.State_id).ToString()
                }).ToList();

            ViewBag.viewStates = stateList;

            return View();
        }
tereško
  • 58,060
  • 25
  • 98
  • 150
Ufuk Doğan
  • 47
  • 2
  • 9
  • Have you tried to debug the action? When are you getting the 500? – Camilo Terevinto Dec 08 '15 at 00:22
  • Why are you not binding to a model and submitting you model. You ajax options specify the return type as json but your returning html –  Dec 08 '15 at 00:24
  • @cFrozenDeath I put debugger to View, when I go to inspect mode and press the button, at the console tab it writes that, – Ufuk Doğan Dec 08 '15 at 00:26
  • @cFrozenDeath POST http://localhost:56436/Home/SignUp 500 (Internal Server Error) – Ufuk Doğan Dec 08 '15 at 00:27
  • I don't know how can I do, what should I do @StephenMuecke – Ufuk Doğan Dec 08 '15 at 00:56
  • You get the error because `dataType: 'json'` means you expect the return type to be json, but your not returning json, your returning html. Change it to `dataType: 'html'` and the error will disappear. But you don't do anything with the view you return so what is the point of this. And why are you not using a model and posting back your model anyway? I have no idea what you think this code is trying to do. –  Dec 08 '15 at 01:00
  • @StephenMuecke hi again, I created a model and I fill the – Ufuk Doğan Dec 08 '15 at 02:25
  • @StephenMuecke and with this model I can add state names to my dropdownList. I run the program and the states names are coming, that's what i want :) But when i click the button the alert comes "2", that means error, i did not change anything my HttpPost SignUp, it same code. What should I do now. By the way I tried to change my datatype json to html but it didn't work :( – Ufuk Doğan Dec 08 '15 at 02:28
  • (1). You must change it to `dataType: 'html'` because it would throw an error. (2) There is nothing else in your code that you have shown that would cause an error (although the property names should not be quoted - its just `data: { tcNo: tcNo, nameSurname: nameSurname, .... }`. But your code does not make sense. Your not doing anything in the POST method - just returning a view which you do not do anything with (and what is the point - why would you want to stay on the same page an allow the user to login again?) –  Dec 08 '15 at 04:08
  • @StephenMuecke hi, I changed data type to html and it didn't work again :(. In my HttpPost part i will create a new user using the datas from coming ajax but ajax doesn't send any data to controller. That's why the controller part is empty. – Ufuk Doğan Dec 08 '15 at 12:19

3 Answers3

1

500 error code means Internal server error. That means your server side code is crashing in the HttpPost Signup method.

If you open the network tab of your browser,and click on the response of the request you made, you will be able to see the response (Exception details returned by asp.net mvc). That will help you to identify the issue.

In your HttpPost action method, you called return View() ,which is going to return the Signup.cshtml razor view. But in the signup view, similar to our GET action, It is going to look for ViewBag.viewStates to render the state dropdown. But we did not set that in our HttpPost Signup method. So it will end up with a null reference exception when razor tries to render the view.

Remember, Http is stateless. One request does not have no idea what happened in the previous request. That means, the request for HttpPost action does not have any idea of the ViewBag items you set in the previous request(GET request).

Typically, for action methods which serves ajax posts, It is good to return a JSON response.

So instead of return View(), return a json structure.

[HttpPost]
public ActionResult SignUp(string tcNo, string nameSurname, string eMail, 
           string number,string secretQuestionAnswer, string password, 
                                         string passwordVerify, string stateValue)
{

    return Json(new {status = "success"});
}

This is going to return a json structure like

{"status" : "success"}

And you can read that in your success event handler

success: function (msg) {
               console.log(msg);
               if(msg.status==="success")
               {
                   alert("Saved");
               }
        }

Also, looks like you have a lot of parameters being posted to the Signup method, instead of writing so many params, you should use a view model. Here is an example on how to do that.

Community
  • 1
  • 1
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • thanks for your help, when I changed my code like yours I didn't get any errors, but there is a problem. The problem is ajax doesn't send my data to my controller. What should I do for sending data view to controller? – Ufuk Doğan Dec 08 '15 at 13:28
  • How do you know it is not sending ? Did you check the network tab of the browser ? Are you getting a 404 error ? What exactly is not working. I tried the exact same code in a new project and it worked fine. So there must be something different you are doing. – Shyju Dec 08 '15 at 19:10
  • when I put breakpoint to my HttpPost Signup method, I can't see the values of the parameters, but I see "Saved" alert in my view page – Ufuk Doğan Dec 08 '15 at 19:48
  • Which version of mvc are you using? I tried the exact same code and it worked fine. can you create a new project and try this and share the code ? – Shyju Dec 08 '15 at 19:51
  • https://github.com/Ufukdogann/DummyProject.git this is my git for this project, you can clone it, it is public. It's MVC 5. When I put breakpoint in the HttpPost SignUp method it is not stopping, it is just show "Saved" alert, that's why I can't see the parameters, because it didn't stop at debugging point. If you want I can use Teamviewer too, ufukdogan1993@hotmail.com it's my facebook e-mail, if you search my mail in search bar you can easily find me, I don't want to write my Teamviewer Id here – Ufuk Doğan Dec 08 '15 at 20:09
  • It totally worked for me. See http://s13.postimg.org/tv4olgnvb/Http_Post_working_screenshot.png . I think you need to clean your project/solution and rebuild. I think there are some old dlls still there in the bin folder which is causing the "not hitting the breakpoint" issue – Shyju Dec 08 '15 at 21:07
  • did you just clone my project and run the signUp page? – Ufuk Doğan Dec 08 '15 at 23:26
  • Yes. I did clean the solution and rebuilt and it worked for me. Try deleting the stuff from bin folder and rebuild again and see what happens. – Shyju Dec 08 '15 at 23:27
  • which ones i should delete? can you send me your bin folder? – Ufuk Doğan Dec 08 '15 at 23:29
  • contents of bin folder of your web project. When you rebuild it should be regenerated. – Shyju Dec 08 '15 at 23:31
  • still I can't get data :( I am gonna be crazy. That's my teamviewer id and password, id= 538 202 533, password = gt7r37 Please connect to me and we can fix it together – Ufuk Doğan Dec 08 '15 at 23:34
  • Did you delete the bin folder and rebuild your project ? – Shyju Dec 08 '15 at 23:36
  • Yeah, I did and rebuilded. It automaticly comes again but still I can't get data. Please use teamviewer and connect me, I am trying to solve this problem 36 hours :( – Ufuk Doğan Dec 08 '15 at 23:38
  • Sorry ! I can't use teamviewer. I suggest you to create a new project and paste only the coded for the signup.(Exclude the state dropdown) and see whether that works. – Shyju Dec 08 '15 at 23:58
  • okey, I am doing it now, by the way I added you at Twitter, if you add me too, I can send you direct message, UfukDoan5 at twitter – Ufuk Doğan Dec 09 '15 at 00:03
  • I did what you say and it worked, I can get data at my controller but I want to select cities from database with combobox. How can I do that? – Ufuk Doğan Dec 09 '15 at 00:17
  • Okay, got it. You are suggesting me rewrite my project at different solution? – Ufuk Doğan Dec 09 '15 at 00:20
  • hi, the problem is starts again, I get success alert but my breakpoint at the HttpPost is not working. I can't get data again – Ufuk Doğan Dec 09 '15 at 01:41
0

Instead of returning a view from the controller return a JSON result and parse the result and bind it to the dropdown.

Since you are trying to retrieve data from the HTTPGet controller, you should be using the HTTP method of Get.

    [HttpGet]
    public JSONResult SignUp()
    {
        return Json(resultset, JsonRequestBehavior.AllowGet);
    }

    success: function (msg) {
        // parse msg and bind to dropdown
    },

Try using JSON.NET

For a detailed read

rahul
  • 184,426
  • 49
  • 232
  • 263
  • thank you, but i have a question. When I change code like yours View alerts "bsg" that's what i want. But the data is not coming to controller side. I try 2 times its all null, but alerts "bsg". – Ufuk Doğan Dec 08 '15 at 00:34
  • Make sure that you controller method receives all the parameters and process them and returns HTTP status 200 from the server – rahul Dec 08 '15 at 00:35
  • to be clear, I should change my HttpGet method type to JsonResult, and if it's success I should change the success part at the View. What should resultset be? where should I declare it? – Ufuk Doğan Dec 08 '15 at 00:45
0

As mentioned above, http 500 is because of an exception in .Net code.Are you getting this in development. If so give the details of exception. You may attached to W3Wp.exe if you are doing it in some different way.

If this is hosted in dev / QA servers, use remote debugging mechanism. In production look at windows eventviewer. Sometimes you will see what is the exception. Once the exception is visible, just google or post it here.

http://www.codeproject.com/Articles/38132/Remote-IIS-Debugging-Debug-your-ASP-NET-Applicatio

Joy George Kunjikkuru
  • 1,495
  • 13
  • 27