0

I use MVC razor to render the model below.

@Html.HiddenFor(u => u.FormNo, new { @ng_model = "formData.formno" })

When source code is viewed, the html input has a value.

<input id="FormNum" name="FormNum" ng-model="formData.formno" type="text" value="154S00017">

but angular returns this as a blank value in the controller.

   var url;
var controller = 'Inbox';
var action = 'Get_RCTS_FormHistory';
var RCTS = angular.module('RCTS', []);

    RCTS.controller('historyController', function ($scope, $http) {
        $scope.formData = {};
        $scope.formData.formno = '';
        url = "/" + controller + "/" + action + "?FormNo=" + $scope.formData.formno;
       alert(url)
        $http.get(url).success(function (data) {

            $scope.logs = data;


        });
    });

And when debugged in Visual studio.

debug

I'm fairly new to angular and this really irritates me. I tried adding a document.ready() function there on the controller but it also returned an error.

Thanks

I resolved this by assigning the value from another html input.

$scope.formData.formno = $('#FormNo').val();

and ultimately resolved it by using

@Html.HiddenFor(u => u.FormNo, new { @ng_model = "formData.formno",@ng_init=@Model.FormNo }) 

from Razor view.

cafekun
  • 158
  • 2
  • 13
  • 1
    you specifically have `$scope.formData.formno = '';` in your controller, of course it will be empty. – Claies Aug 19 '16 at 07:53
  • 1
    also, angular doesn't set the values for `ng-model` from the `value` on an input; if you really must set the value from the server side, you would either need to set the value as a global variable (not recommended) or use `ng-init`. see http://stackoverflow.com/a/13771205/2495283 – Claies Aug 19 '16 at 07:57
  • @Claies yeah I placed that line of code there with my testing because even without it, it still didn't give me the value. – cafekun Aug 19 '16 at 07:58

1 Answers1

1

You are not updating the value of scope variable

$scope.formData.formno = 'cakefun';
Nikhil Kumar K
  • 1,089
  • 10
  • 13
  • ok, I get the approach now. I used JQuery to update the model from the controller. $scope.formData.formno = $('#FormNo').val(); Thanks! – cafekun Aug 19 '16 at 07:55
  • @cafekun while that approach *works*, it's a bit ugly, it's not efficient, and you are really not using angular in it's intended design paradigm, which is to avoid interacting with the DOM as much as possible. – Claies Aug 19 '16 at 08:00
  • @Claies what do you think could be done? I really wanted to use Razor to render my view. Any help will be appreciated. – cafekun Aug 19 '16 at 08:01
  • 1
    refer to my other comment; setting the variable on the server side is counter to the way angular is designed, but if you must set the value in this manner, use `ng-init`. – Claies Aug 19 '16 at 08:03
  • @Claies I'll try once more by placing ng-init. Thank you so much! – cafekun Aug 19 '16 at 08:15