0

I am working on a project that uses ASP.NET MVC and AngularJS, i am trying to use time input type to set and get time from database i am using code first approach , my question is i want to get the time from database then bind it to input time, i inserted the time successfully to the database but i have problem i can not bind it with the input time control.

**Model**

 public class Branches
 {
  public int Branch_ID { get; set; }
  public string Branch_Name { get; set; }
  public string Branch_Address { get; set; }
  public string Branch_email { get; set; }
  public string Branch_Notes { get; set; }
  [DataType(DataType.Time)]
  [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = @"{0:hh\:mm}")]
  public TimeSpan Branch_TimeFrom { get; set; } 
  [DataType(DataType.Time)]
  [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = @"{0:hh\:mm}")]
  public TimeSpan Branch_TimeTo { get; set; } 
 }

**Controller**



       public class BranchesController : Controller
       {

           private IRepositoryBase<Branches> BrancheRepository;

         public BranchesController()
         {
            this.BrancheRepository = new BranchesRepository(new HrmDBContext());
          }
         public BranchesController(IRepositoryBase<Branches> brancheRepository)
         {
            this.BrancheRepository = brancheRepository;
          }

         // GET: Branches
          [HttpGet]
          public ActionResult Index()
          {

           return View();
          }
          [HttpPost]
          public JsonResult Create(Branches branch)
         {
            try
           {
              if (ModelState.IsValid)
             {

                  BrancheRepository.Create(branch);
                   //var branches = BrancheRepository.GetAll();

                    //return Json(new
                   //{
                  //    d = true,
                  //    pv = RazorToString(this, "~/views/Branches/list.cshtml", branches),

                  //}, JsonRequestBehavior.AllowGet);
                  return Json(new { success = true });

            }
            else
            {
                  return Json(new { success = false });
             }
         }
          catch (DataException  dex)
          {
             ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem 
             persists contact your system administrator.");
             return Json(new { success = false });
           }

             //  return View(branch);
           }
           [HttpPost]
           public JsonResult Edit(Branches branch)
           {
              try
              {
                  if (ModelState.IsValid)
                  {

                      BrancheRepository.Update(branch);
                      return Json(new { success = true });

                   }
                  else
                  {
                      return Json(new { success = false });
                   }
                }
              catch (DataException  dex )
              {
                   //Log the error (uncomment dex variable name after DataException and add a line here to write a log. 
                   ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.");
                  return Json(new { success = false });

                }
             }
         }
**FetchBranchData.js**

 var app = angular.module('myapp', []);

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

    //get All Branches
    this.getAllBranches = function () {
        return $http.get("Branches/GetAllBranches");
    };

    //$http.get(url).then(response) {
    //    var data = response.data;
    //    data.Branch_TimeFrom = new Date(data.Branch_TimeFrom);
    //    data.Branch_TimeTo = new Date(data.Branch_TimeTo);
    //    $scope.data = data;
    //});

    //add new Branch
    this.save = function (Branch) {        
        var request = $http({
            method: 'post',
            url: '/Branches/Create',
            data: Branch
        });
        return request;
    };

    //update Employee records
    this.update = function (Branch) {
        var updaterequest = $http({
            method: 'post',
            url: '/Branches/Edit',
            data: Branch
        });
        return updaterequest;
    };


});

app.controller("branchcontroller", function ($scope, myService) {
    getAllBranches();
    function getAllBranches() {
        var getData = myService.getAllBranches();
        getData.then(function (response) {
            $scope.Branches = response.data;
        }, function (error) {
            console.log(error);
            alert('Error in getting records');
        });
    };


    //save Branch data
    $scope.save = function () {
        debugger
        var Branch = {
            Branch_Name: $scope.Branch_Name,
            Branch_Address: $scope.Branch_Address,
            Branch_email: $scope.Branch_email,
            Branch_Notes: $scope.Branch_Notes,
            Branch_TimeFrom: moment($scope.Branch_TimeFrom).format('HH:mm:ss'),
            Branch_TimeTo: moment($scope.Branch_TimeTo).format('HH:mm:ss'),
            Branch_Manager: $scope.Branch_Manager,
            Branch_Phone: $scope.Branch_Phone,
            saturday: $scope.saturday
        };

        var saverecords = myService.save(Branch);
        saverecords.then(function (response) {
            if (response.data.success === true) {
                getAllBranches();
                alert("Branch added successfully");
                $scope.resetSave();
            }
            else { alert("Branch not added."); }
        },
            function () {
                alert("Error occurred while adding branch.");
            });
    };

    //reset controls after save operation
    $scope.resetSave = function () {

        $scope.Branch_Name = '';
        $scope.Branch_Address = '';
        $scope.Branch_email = '';
        $scope.Branch_Notes = '';
        $scope.Branch_TimeFrom = '';
        $scope.Branch_TimeTo = '';
        $scope.Branch_Manager = '';
        $scope.Branch_Phone = '';
        $scope.saturday = '';
    };


    //get single record by ID
    $scope.getForUpdate = function (Branch) {
        debugger
        $scope.Branch_ID = Branch.Branch_ID;
        $scope.Branch_Name = Branch.Branch_Name;
        $scope.Branch_Address = Branch.Branch_Address;
        $scope.Branch_email = Branch.Branch_email;
        $scope.Branch_Notes = Branch.Branch_Notes;
        $scope.Branch_TimeFrom = moment(Branch.Branch_TimeFrom).format('hh:mm:ss a');
        $scope.Branch_TimeTo = moment(Branch.Branch_TimeTo).format('hh:mm:ss a'); 
        $scope.Branch_Manager = Branch.Branch_Manager;
        $scope.Branch_Phone = Branch.Branch_Phone;
        $scope.saturday = Branch.saturday;
    };

     //update Branch data
    $scope.update = function () {
        var Branch = {
            Branch_ID: $scope.Branch_ID,
            Branch_Name: $scope.Branch_Name,
            Branch_Address: $scope.Branch_Address,
            Branch_email: $scope.Branch_email,
            Branch_Notes: $scope.Branch_Notes,
            Branch_TimeFrom: $scope.Branch_TimeFrom,
            Branch_TimeTo: $scope.Branch_TimeTo,
            Branch_Manager: $scope.Branch_Manager,
            Branch_Phone: $scope.Branch_Phone,
            saturday : $scope.saturday 
        };
        var updaterecords = myService.update(Branch);
        updaterecords.then(function (response) {
            if (response.data.success === true) {
                getAllBranches();
                alert("Branch updated successfully");
                $scope.resetUpdate();
            }
            else {
                alert("Branch not updated.");
            }
        },
            function () {
                alert("Error occured while updating Branch record");
            });
    };

    //reset controls after update
    $scope.resetUpdate = function () {
        $scope.Branch_Name = '';
        $scope.Branch_Address = '';
        $scope.Branch_email = '';
        $scope.Branch_Notes = '';
        $scope.Branch_TimeFrom = '';
        $scope.Branch_TimeTo = '';
        $scope.Branch_Manager = '';
        $scope.Branch_Phone = '';
        $scope.saturday = '';
    };
    };

Index.cshtml

<div class="container" ng-controller="branchcontroller">
    <table class="table table-bordered">
                    <thead style="background-color:lightblue;">
                        <tr>
                            <th>Branch Address</th>
                            <th>Branch Email</th>
                            <th>Branch Name</th>
                            <th>Branch Notes</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr ng-repeat="branche in Branches">
                            <td>{{branche.Branch_Address}}</td>
                            <td>{{branche.Branch_email}}</td>
                            <td>{{branche.Branch_Name}}</td>
                            <td>{{branche.Branch_Notes}}</td>
                            <td style="width:200px;">
                                <a href="#"
                                   class="btn btn-info"
                                   data-toggle="modal"
                                   data-target="#Update"
                                   ng-click="getForUpdate(branche)">
                                    Update
                                </a>
                                <a href="#" class="btn btn-danger"
                                   id="btnDelete"
                                   data-toggle="modal"
                                   data-target="#deleteDialog"
                                   ng-click="getForDelete(branche)">
                                    Delete
                                </a>
                            </td>
                        </tr>
                    </tbody>
                </table>
  @*Upadate Branch records*@
     
        <div class="modal" id="Update" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h3 class="text-info">Update Existing Branch</h3>
                    </div>
                    <div class="modal-body" style="margin-left:20px">
                        @*Update Employee form starts here...*@
                        <form class="form-horizontal" name="UpdateBranchForm">
                            <div class="form-group">
                                <input class="form-control" readonly="readonly" name="Branch_ID" ng-model="Branch_ID" type="hidden" placeholder="Branch ID" />
                            </div>
                            <div class="form-group">
                                <label class="control-label"> Branch Address</label>
                                <input class="form-control" name="Branch_Address" ng-model="Branch_Address" type="text" placeholder="Branch Address" />

                            </div>
                            <div class="form-group">
                                <label class="control-label"> Branch email</label>
                                <input class="form-control" name="Branch_email" ng-model="Branch_email" type="email" placeholder="Branch email" />

                            </div>
                            <div class="form-group">
                                <label class="control-label"> Branch Name</label>
                                <input class="form-control" name="Branch_Name" ng-model="Branch_Name" type="text" placeholder="Branch Name" />

                            </div>
                            <div class="form-group">
                                <label class="control-label"> Branch Manager</label>
                                <input class="form-control" name="Branch_Name" ng-model="Branch_Manager" type="text" placeholder=" Branch Manager" />

                            </div>
                            <div class="form-group">
                                <label class="control-label"> Branch Phone</label>
                                <input class="form-control" name="Branch_Name" ng-model="Branch_Phone" type="text" placeholder="Branch Phone" />

                            </div>
                            <div class="form-group">
                                <label class="control-label"> Branch Notes</label>

                                <textarea class="form-control" name="Branch_Notes" ng-model="Branch_Notes" placeholder="Branch Notes"></textarea>

                            </div>
                            <div class="form-group">
                                <label class="control-label"> Time From</label>

                                <input ng-model="Branch_TimeFrom" type="time"  name="Branch_TimeFrom" placeholder="HH:mm">

                            </div>
                            <div class="form-group">
                                <label class="control-label"> Time To</label>

                                <input ng-model="Branch_TimeTo" type="time" name="Branch_TimeTo" placeholder="HH:mm">

                            </div>
                            <div class="form-group">
                                <label class="control-label"> saturday</label>

                                <input ng-model="saturday" type="checkbox" name="saturday" placeholder="saturday">

                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" id="btnUpdate" data-dismiss="modal" ng-click="update()">
                            Update
                        </button>
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
</div>

here i want to get time from database then display it in input type time

enter image description here

here is the time that i get it from database then i want it to display to input type time

enter image description here

1
  • This looks like the same code as this question posted by @hashim. Are you using two accounts to post questions? Commented Jan 7, 2020 at 3:15

1 Answer 1

0

The AngularJS framework needs to bind JavaScript Date objects:

$http.get(url).then(response) {
    var data = response.data;
    data.Branch_TimeFrom = new Date(data.Branch_TimeFrom);
    data.Branch_TimeTo   = new Date(data.Branch_TimeTo);
    $scope.data = data;
});
<label class="control-label"> Branch Notes</label>
<textarea ng-model="data.Branch_Notes">
</textarea>

<label class="control-label"> Time From</label>
<input ng-model="data.Branch_TimeFrom" type="time">

<label class="control-label"> Time To</label>
<input ng-model="data.Branch_TimeTo" type="time">

From the Docs:

The model must always be a Date object, otherwise AngularJS will throw an error. Invalid Date objects (dates whose getTime() is NaN) will be rendered as an empty string.

For more information, see

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.