0

I am working on an MVC application and I can not understand why I am getting few values as 'null'.

What should be done to serialize the date value from JavaScript to C#.

View code:

@{
    Layout = null;
 }

<!DOCTYPE html>

<html ng-app="mvcCRUDApp">
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>


    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script src="~/Scripts/angular.min.js"></script>

    <script type="text/javascript">
        var app = angular.module("mvcCRUDApp", []);

        app.service("crudAJService", function ($http) {

            // save Customer
            this.saveCustomer = function (objCustomer) {
                var response = $http({
                    method: "post",
                    url: "Customer/PostDataResponse",
                    data: JSON.stringify(objCustomer),
                    dataType: "json"
                });
                return response;
            }


        });

        app.controller("mvcCRUDCtrl", function ($scope, crudAJService) {

            $scope.AddCustomer = function () {                

                var objCustomer = {
                    id: "0",
                    Name: $('#txtName').val(),
                    Surname: $('#txtSurname').val(),
                    BirthDate: $('#txtBirthDate').val(),
                    Gender: $('#txtGender').val(),
                    CityId: $('#drpCity').val()
                };

                var getBookData = crudAJService.saveCustomer(objCustomer);
                    getBookData.then(function (msg)
                    {
                        alert(msg.data);                        
                    }, function () {
                        alert('Error in updating book record');
                    });
                }                         
        });

    </script>

    <script>

        $(document).ready(function ()
        {
            $("#drpState").change(function () {
                $("#drpCity").empty();
                $("#drpCity").append('<option value="0">-Select-</option>');
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("SelectCities")',
                    dataType: 'json',
                    data: { Stateid: $("#drpState").val() },
                    success: function (cities) {
                        // cities contains the JSON formatted list
                        // of state id passed from the controller
                        $.each(cities, function (i, city)
                        {
                            $("#drpCity").append('<option value="'
                             + city.id + '">'
                             + city.Name + '</option>');
                        });
                    },
                    error: function (ex)
                    {
                        alert('Failed to retrieve states.' + ex);
                    }
                });
                return false;
            })
        });
    </script>
</head>
<body>
    <div ng-controller="mvcCRUDCtrl">
        <fieldset>
            <table>
                <tr><td>@Html.Label("Name")</td><td>@Html.TextBox("txtName")</td><td>@Html.Label("Surname")</td><td>@Html.TextBox("txtSurname")</td></tr>
                <tr><td>@Html.Label("BirthDate")</td><td>@Html.TextBox("txtBirthDate")</td><td>@Html.Label("Gender")</td><td>@Html.TextBox("txtGender")</td></tr>
                <tr>
                    <td>State</td>
                    <td>@Html.DropDownList("drpState", ViewBag.StateCollection as List<SelectListItem>)</td>
                    <td>City</td>
                    <td>@Html.DropDownList("drpCity", ViewBag.CityCollection as List<SelectListItem>)</td>
                </tr>
                <tr><td><input type="submit" value="Submit" ng-click="AddCustomer()" /></td></tr>
            </table>
        </fieldset>
    </div>
</body>
</html>

Following is THE CODE OF CONTROLLER 

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DutchProject.Models;

namespace DutchProject.Controllers
{
    public class CustomerController : Controller
    {

        DutchEntities db = new DutchEntities();

        //
        // GET: /Customer/

        public ActionResult Index()
        {
            List<SelectListItem> States = new List<SelectListItem>();

            var lstStates = db.States.ToList();

            States.Add(new SelectListItem { Text = "-Select-", Value = "0" });
            foreach (var item in lstStates)
            {
                States.Add(new SelectListItem { Text = item.Name, Value = item.id.ToString() });
            }

            ViewBag.StateCollection = States;


            List<SelectListItem> Cities = new List<SelectListItem>();

            Cities.Add(new SelectListItem { Text = "-Select-", Value = "0" });
            ViewBag.CityCollection = Cities;



            return View();
        }

        [HttpPost]
        public JsonResult SelectCities(int Stateid)
        {
            IEnumerable<City> cities = db.Cities.Where(stat => stat.StateId == Stateid);    // .Where(stat => stat.country_id == id);
            return Json(cities);
        }

        [HttpPost]
        public ContentResult PostDataResponse(Customer objCustomer)
        {
            objCustomer.BirthDate = DateTime.Now;
            objCustomer.Gender = 1;

            db.Customers.Add(objCustomer);
            db.SaveChanges();

            return Content("First name: " + Request.Form["firstName"] +
                " | Last name: " + Request.Form["lastName"] +
                " | Age: " + Request.Form["age"]);
        }

    }
}
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Andy Eng
  • 61
  • 1
  • 2
  • 7
  • Actually, the code does not exactly explain what you are doing! Which values sometimes get null? did you try something to find out which section of the code is the problematic one? As is, your question is too unspecific! – jkalden Oct 29 '15 at 18:34
  • half this code is MVC and the other half is angularjs. You have suggested that you are having an issue with the MVC code but you have tagged the question as an angular problem. From a higher level perspective, if you are going to use angular, then use angular everywhere, don't mix it with MVC like this. Aside from that, you may want to clarify your question a bit, and re-tag it. – Claies Oct 31 '15 at 20:34
  • reviewing the code a bit more, I don't even think that angular is doing anything at all in this code. it seems to be duplicated code, and there are no angular bindings or function calls in the HTML. – Claies Oct 31 '15 at 20:37
  • I really would recommend studying a bit more if you intend to actually use angular; code like `Name: $('#txtName').val(),` isn't angular, it's JQuery, and it has *no business* in an angular controller. Based on the way this code was written, angular may as well not even be included in the project. – Claies Nov 01 '15 at 00:57

1 Answers1

0

ASP.NET MVC passes a null value in the controller action for a value that is not valid. It may help to validate the date beforehand, just to be sure the value is valid.

Also, it might help to assign a date instead of string:

...
var objCustomer = {
                        id: "0",
                        Name: $('#txtName').val(),
                        Surname: $('#txtSurname').val(),
                        BirthDate: new Date($('#txtBirthDate').val()),
                        Gender: $('#txtGender').val(),
                        CityId: $('#drpCity').val()
                    };
...
Community
  • 1
  • 1
Martin Staufcik
  • 8,295
  • 4
  • 44
  • 63