Как получить время, используя AngularJs, а затем связать его с вводом времени из представления в контроллер - PullRequest
0 голосов
/ 07 января 2020

Я работаю над проектом, который использует ASP. NET MVC и AngularJS, я пытаюсь использовать тип ввода времени, чтобы установить и получить время из базы данных, которую я использую Первый подход кода, мой вопрос, я хочу получить время из базы данных, а затем связать его с вводом времени, я успешно вставил время в базу данных, но у меня есть проблема, я не могу связать его с контролем времени ввода.

**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.cs html

<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>

здесь я хочу получить время из базы данных, а затем отобразить его во времени ввода типа

enter image description here

вот время, когда я получаю его из базы данных, затем я хочу, чтобы оно отображало время ввода типа

enter image description here

1 Ответ

0 голосов
/ 07 января 2020

Каркас AngularJS должен связывать JavaScript Date объекты:

$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">

Из документов:

Модель всегда должна быть объектом Date, в противном случае AngularJS выдаст ошибку. Недопустимые Date объекты (даты, для которых getTime() равно NaN) будут отображаться в виде пустой строки.

Для получения дополнительной информации см.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...