0

I write this ajax in view page in asp.net mvc:

<script type="text/javascript">
        $(document).ready(function () {

            $("#Shareitem").click(function (e) {
                var serviceURL = '/Register/FirstAjax';
                $.ajax({
                    type: "POST",
                    url: serviceURL,
                    data: '123',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: successFunc,
                    error: errorFunc
                });
                function successFunc(data, status) {
                    alert(data);
                }
                function errorFunc() {
                    alert('error');
                }
            });
        });
    </script>


and this is my action method in controller:

[HttpPost]
        public ActionResult FirstAjax(string value)
        {
            string test = value.Trim();
            return Json("PROF.VALI", JsonRequestBehavior.AllowGet);
        }


but in this line:

string test = value.Trim();


get this error:

An exception of type 'System.NullReferenceException' occurred in UserRegister.dll but was not handled in user code


How can i solve that?thanks.

behi behi
  • 137
  • 2
  • 3
  • 11
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Divyang Desai Oct 24 '16 at 12:18
  • Possible duplicate of [JQUERY ajax passing value from MVC View to Controller](http://stackoverflow.com/questions/8486132/jquery-ajax-passing-value-from-mvc-view-to-controller) – CodeCaster Oct 24 '16 at 12:20
  • See [this question](http://stackoverflow.com/questions/8486132/jquery-ajax-passing-value-from-mvc-view-to-controller), you'll have to match the parameter name. – CodeCaster Oct 24 '16 at 12:20
  • `data: JSON.stringify({ value: '123' }),` –  Oct 24 '16 at 12:21
  • @StephenMuecke that work my friend,please post your solution to vote up you! – behi behi Oct 24 '16 at 12:23

1 Answers1

1

You need to send the data in a format that matches the name of the parameter of the method your posting to. Change the ajax data option to

data: JSON.stringify({ value: '123' }),

Alternatively, you can just use

data: { value: '123' },

and remove contentType: "application/json; charset=utf-8", option so it uses the default ('application/x-www-form-urlencoded; charset=UTF-8')