Value or form.value is undefined - angular7

I am trying to define undefined values for a angular form as nulls until the form data is entered. I am getting ERROR TypeError: Cannot read property 'value' of undefined. Which I know comes from having my values not defined rather then nulls. I have them defined in the file but I am not sure why the form is not picking linking them.
I have tried multiple suggestion from Stackoverflow, Youtube, and The Angular Documents.
Associate.component.ts
constructor(private service: AssociateService) { }
ngOnInit() { //put null check
this.resetForm();
}
resetForm(form?: NgForm) {
if(form != null)
form.resetForm();
this.service.formData = {
EmployeeID: null,
FirstName: '',
MiddleName: '',
LastName: '',
EmployeeType: null,
EmployeeStatus: null,
EmployeeLevel: null,
EmployeeRole: null,
Proactive: false
}
}
onSubmit(form: NgForm) {
debugger;
if (form.value.EmployeeID == null)
this.insertRecord(form);
else
this.updateRecord(form)
}
Assocaite.component.html
<form #form="ngForm" autocomplete="off">
<div style="margin-left: 10px">
<div class="form-group">
<label>EMPLOYEEID</label>
<input name="EmployeeID" #EmployeeID=ngModel [(ngModel)]="service.formData.EmployeeID" class="form-control">
</div>
I have the rest of the Html for all the the other formData. Just wanted trim the code as much as possible.
I need form.value.EmployeeID to pull the values of this.service.formData. Any help or guidance would be amazing. I have been stuck on this for 2 days now.

Another approach could be:
Step1- Create model object Employee.model.ts
export class employee{
employeeID:number,
name:string,
lastName:string,
...
...
...
}
Step2: Initialize in component.ts
emp:Employee | undefined;
constructor(private service: AssociateService) {
this.emp= new Employee();
}
onSubmit() {
if (form.valid && this.emp.EmployeeID == undefined)
this.insertRecord(this.emp);
else
this.updateRecord(this.emp)
}
Step3- Html file finding of model binding
<input name="EmployeeID" #EmployeeID=ngModel
[(ngModel)]="emp.EmployeeID" class="form-control">

Related

New value in HTML.DropDownListFor(...) not setting in Controller [Post] method?

Hopefully someone can see how to go about this, because I've tried everything I can think of. When the Create() View in my MVC5 application loads I first populate several [SelectList(...)]'s in my Controller (ex.):
ViewBag.Model_Id = new SelectList(db.DBT_MODELS.OrderBy(x => x.MODEL_DESCRIPTION), "MODEL_ID", "MODEL_DESCRIPTION");
I then on my Create() View use this [SelectList(...)] to Populate an Html.DropDownListFor(...):
<div class="form-group">
<span class="control-label col-md-2">Model:</span>
<div class="col-md-4">
#Html.DropDownListFor(model => model.MODEL_ID, (SelectList)ViewBag.Model_Id, htmlAttributes: new { #class = "form-control dropdown", #id = "selectModel" })
#Html.ValidationMessageFor(model => model.MODEL_ID, "", new { #class = "text-danger" })
</div>
<div class="col-md-2">
<div class="btn-group">
<button id="createNewModel" type="button" class="btn btn-success" aria-expanded="false">CREATE NEW</button>
</div>
</div>
<div class="col-md-4">
<div id="createModelFormContainer" style="display:none">
<form action="/createNewModel">
<input type="text" id="textNewModel" name="model_description" placeholder="New Model" />
<input type="button" id="submitNewModel" value="Submit" />
<input type="button" id="cancelNewModel" value="Cancel" />
</form>
</div>
</div>
</div>
Simple enough, and this all works as expected. The problem lies in a bit of extended functionality I've tried to incorporate. My main class has several of these properties which are basically Foreign Key's in my DB. When a User goes in to Create/Edit() an entity in my main Model, I wanted to allow them to be able to add new entities to these foreign tables without needing to navigate away from the current View.
As such, I added (for each foreign property, using (Model) as an example) the code shown above and again directly below with a button to Show/Hide a small form for users to insert a new value and have it added to the DropDownList:
<div class="col-md-2">
<div class="btn-group">
<button id="createNewModel" type="button" class="btn btn-success" aria-expanded="false">CREATE NEW</button>
</div>
</div>
<div class="col-md-4">
<div id="createModelFormContainer" style="display:none">
<form action="/createNewModel">
<input type="text" id="textNewModel" name="model_description" placeholder="New Model" />
<input type="button" id="submitNewModel" value="Submit" />
<input type="button" id="cancelNewModel" value="Cancel" />
</form>
</div>
</div>
My submitNewModel() click event below gets the user's inputted new value and then uses a JSON call to a Controller Method to add it in the Database Table. This new value (and new ID for it) are then returned, the form for the DropDownList is reset, and I set the DropDownList's current value as the newly added one:
$('#createNewModel').click(function () {
$('#createModelFormContainer').show();
})
$('#cancelNewModel').click(function () {
$('#createModelFormContainer').hide();
})
$('#submitNewModel').click(function () {
var form = $(this).closest('form');
var data = { description: document.getElementById('textNewModel').value };
$.ajax({
type: "POST",
dataType: "JSON",
url: '#Url.Action("createNewModel", "INV_ASSETS")',
data: data,
success: function (resp) {
if (resp.ModelExists)
{
alert("Model [" + resp.Text + "] already exists. Please select from the DropDown.");
} else {
$('#selectModel').append($('<option></option>').val(resp.MODEL_ID).text(resp.Text));
form[0].reset();
$('#createModelFormContainer').hide();
var count = $('#selectModel option').size();
$('#selectModel').prop('selectedIndex', count - 1);
$('#selectModel').val(resp.MODEL_ID);
//document.getElementById('selectModel').value = resp.MODEL_ID; - Shows dropdown as blank [ ] once executed.
}
},
error: function () {
alert("ERROR - Something went wrong adding new Model [" + resp.Text + "]!");
$('#createModelFormContainer').hide();
}
});
//reloadForNewEntity();
});
The createNewModel() method that is called in my Controller:
public JsonResult createNewModel(string description)
{
DBT_MODELS model = new DBT_MODELS()
{
// ID auto-set during save.
MODEL_DESCRIPTION = description.Trim(),
CREATED_DATE = DateTime.Now,
CREATED_BY = System.Environment.UserName
};
var duplicateModel = db.DBT_MODELS.FirstOrDefault(x => x.MODEL_DESCRIPTION.ToUpper() == model.MODEL_DESCRIPTION.ToUpper());
try
{
if (duplicateModel == null)
{
if (ModelState.IsValid)
{
db.DBT_MODELS.Add(model);
db.SaveChanges();
// Ensure the [model.ID] is properly set after having been saved to and auto-generated in the database.
model.MODEL_ID = db.DBT_MODELS.FirstOrDefault(x => x.MODEL_DESCRIPTION.ToUpper() == model.MODEL_DESCRIPTION.ToUpper()).MODEL_ID;
}
}
else
{
model = duplicateModel;
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
return Json(new { ID = model.MODEL_ID, Text = model.MODEL_DESCRIPTION, ModelExists = (duplicateModel != null) }, JsonRequestBehavior.AllowGet);
}
Visually speaking, everything works as intended up to this point. The problem is when I go to Save the main entity I am Creating/Editing.
Any value that was already in the Foreign Tables, and thus in the DropDownList when the View loads, saves just fine; but if I add a new Foreign Table value for these main entity properties (though visually added and the currently selected values for the individual DropDownLists) the [POST] method then executes with each foreign id value set as 0 (ex. MainClass.Model_ID = "0" vs expected MainClass.Model_ID = "625", MainClass.Type_ID = "0" vs expected MainClass.Type_ID = "17", MainClass.Location_ID = "0" vs expected MainClass.Location_ID = "82", etc.)
Basically if the value selected in the Html.DropDownListFor() is one of my newly added values, the POST controller method always renders the MainClass.*_ID value which the selected Html.DropDownListFor() value corresponds to as "0".
Can anyone point me to how to get this working? I have tried:
Changing how my JavaScript sets the value in the DropDownList after the the JSON call to my Controller Actions returns (ex): //document.getElementById('selectModel').value = resp.MODEL_ID; - Shows dropdown as blank [ ] once executed. vs $('#selectModel').val(resp.MODEL_ID); which visually renders the expected new value in the DropDownList.
On return from the Controller method, setting a new ViewBag variable and then hoping to reference the saved value in the POST method (did not work, the JavaScript rendered my #Viewbag.PostModelID = resp.ModelID as "= resp.ModelID" and threw many expected errors).
EDIT:
[Redacted for N/A]
EDIT2: Good to go. Thanks everyone for the suggestions!
The json data you are returning from your action method is in this format.
{
"ID": 24,
"Text": "IOS",
"ModelExists": false
}
But in your code, you are trying to access MODEL_ID property which does not exist in the resp object.
$('#selectModel').append($('<option></option>').val(resp.MODEL_ID).text(resp.Text));
Change your code to use ID property value
$('#selectModel').append($('<option></option>').val(resp.ID).text(resp.Text));
$('#selectModel').val(resp.ID);
In your controller where you create the new model.. your json object that you're returning is ID, Text, ModelExists, but in your javascript you're setting the val property of the new <option> to MODEL_ID.. these 2 need to match..
So change your javascript to be
.val(resp.ID)
or change the return value in your controller action to
return Json(new { MODEL_ID = model.MODEL_ID, Text = model.MODEL_DESCRIPTION
You're also referencing MODEL_ID here
$('#selectModel').val(resp.MODEL_ID);
so make sure if you don't change your controller action, you update this also

angularJS with MVC call - how to do something other than CRUD?

I've been following web tutorials to try to learn angularJS on a .NET MVC Application. All the tutorials seem to cover getting a list, getting an individual item etc.
What I want to do is allow the user to fill in an email address, I want to verify that email address against the database and return true or false if it existed. I'm then trying to put that value in the scope so I can do something in response to whether its true or false.
I'm using a single page app so this is the login html.
<form name="form" class="form-horizontal">
<div class="control-group" ng-class="{error: form.ValidEmailAddress.$invalid}">
<label class="control-label" for="ValidEmailAddress">Valid Email Address</label>
<div class="controls">
<input type="email" ng-model="item.ValidEmailAddress" id="ValidEmailAddress">
</div>
</div>
<div class="form-actions">
<button ng-click="login()" class="btn btn-primary">
Go!
</button>
<label ng-if="user.isAuthorised">Authorised</label>
<label ng-if="!user.isAuthorised">NotAuthorised</label>
</div>
</form>
In my app.js file I declare a loginCtrl controller when the url was /login so that's all fine. The logic that I'm calling on my button click is this:
var LoginCtrl = function ($scope, $location, $http, AuthorisedUser) {
$scope.login = function() {
var isValidUser = $http.get("/AuthorisedUser/IsValidUser/" + $scope.item.ValidEmailAddress);
$scope.user.isAuthorised = isValidUser;
} };
Which is then calling an MVC AuthorisedUserController class method:
public bool IsValidUser(string id)
{
var list = ((IObjectContextAdapter)db).ObjectContext.CreateObjectSet<ApprovedUser>();
var anyItems = list.Any(u => u.ValidEmailAddress == id);
return anyItems;
}
So it vaguely seemed to be working when I put in a value like "aaa" into the textbox. But as soon I try putting in an email address the value is undefined. Maybe I'm supposed to be doing a post but the only thing I can successfully hit my .NET controller with is by using get.
I'm sure I'm missing fundamental knowledge and potentially tackling this in the wrong way.
In case it helps I've created a module and defined factories like this:
var EventsCalendarApp = angular.module("EventsCalendarApp", ["ngRoute", "ngResource"]).
config(function ($routeProvider) {
$routeProvider.
when('/login', { controller: LoginCtrl, templateUrl: 'login.html', login: true }).
otherwise({ redirectTo: '/' });
});
EventsCalendarApp.factory('AuthorisedUser', function ($resource) {
return $resource('/api/AuthorisedUser/:id', { id: '#id' }, { isValidUser: { method: 'GET' } });
});
One of my questions is - should I be accessing the controller method using the $http object, or is there a way of using my factory declaration so that I can go something like:
AuthorisedUser.IsValidUser($scope.item.validEmailAddress)
I know in the tutorial I was following I could do stuff like:
CalendarEvent.save()
to be able to call a CalendarEventController post method.
What i think is, your get() function will return a promise. and you can't assign promise like this. so better try this approch once. I hope, it'd work. if not please let me know...
here I assume your first,second and third snippet of code works fine...
$http.get("/AuthorisedUser/IsValidUser/" + $scope.item.ValidEmailAddress).success(function (result, status) {
var isValidUser=result;
$scope.user.isAuthorised = isValidUser;
$scope.$apply();
}).error(function (result, status) {
//put some error msg
});

are jqueryvalidation rules using OR possible?

I'm creating a small jquery mobile project and have decided to use jqueryvalidation http://jqueryvalidation.org/ for form validation. I have a popup box where the user enters a number which is either their phone or email (unfortunately this has to stay like this because of the database) so I want to use the validation to say that the field must either contain email: or digits:.
Do you know if this is possible? Or a workround? Using depends: won't work either in this case as there is no conditional that will work on every database (the primary phone/email will not always be filled).
<form id='addNumber' action ='' method='post' data-ajax='false'>
<div class="ui-field-contain">
<label for="phoneType">Type</label>
<select name="phoneType" id="phoneType" data-native-menu="false">
<?php echo $phoneInnerOptions; ?>
</select>
</div>
<div class="ui-field-contain">
<label for="phoneNumber">Number</label>
<input type="text" name="phoneNumber" id="phoneNumber" value="">
</div>
<div class="ui-field-contain">
<label for="primary">Primary Contact</label>
<select name="primary" id="primary" data-native-menu="false" >
<option value="1">Primary Phone</option>
<option value="2">Primary Email</option>
<option value="3"></option>
</select>
</div>
<div class='ui-grid-a'>
<div class='ui-block-a'><input type='submit' value='Update' class='ui-btn ui-btn-inline' data-transition='pop' /></div>
<div class='ui-block-b'><a href='#' id="addNumberReset" class='ui-btn' data-rel='back' data-transition='pop'>Cancel</a></div>
</div>
</form>
And the current validation:
$().ready(function() {
// validate add number form
$("#addNumber").validate({
errorPlacement: function(error, element) {
error.insertAfter(element.parent()); // <- make sure the error message appears after parent element (after textbox!)
},
rules: {
phoneNumber: "required",
},
messages: {
phoneNumber: "Please enter a valid phone or email",
}
}); //end validate
});// end function
Any help or advise with this one would be appreciated :)
Your best option in this case is to just write your own rule using the .addMethod() method.
simple example from docs:
jQuery.validator.addMethod("myrule", function(value, element) {
// return 'true' to pass validation or return 'false' to fail validation
return this.optional(element) || /^http:\/\/mycorporatedomain.com/.test(value);
}, "Please specify the correct domain for your documents");
markup to declare this example rule:
rules: {
myfield: {
myrule: true // only passes validation if "http://mycorporatedomain.com" is entered
}
}
simple example from docs using parameters:
jQuery.validator.addMethod("myrule", function(value, element, params) {
// return 'true' to pass validation or return 'false' to fail validation
return this.optional(element) || value == params[0] + params[1];
}, jQuery.validator.format("Please enter the correct value for {0} + {1}"));
markup to declare this example rule:
rules: {
myfield: {
myrule: [5,20] // only passes validation if '25' is entered
}
}
this.optional(element) in both examples makes the field entry "optional". If you also want the field required, just remove this part.
You can browse through the additional-methods.js file to see dozens of real working examples of this method.
Heres the code I ended up using incase anyone else might need it.. thanks for the help on this one sparky
//creating the new rule
//Matches UK landline + mobile, accepting only 01-3 for landline or 07 for mobile to exclude many premium numbers
jQuery.validator.addMethod('phonesUK', function(phone_number, element) {
phone_number = phone_number.replace(/\(|\)|\s+|-/g,'');
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(?:(?:(?:00\s?|\+)44\s?|0)(?:1\d{8,9}|[23]\d{9}|7(?:[45789]\d{8}|624\d{6})))$/);
});
//use phonesUK or standard email
jQuery.validator.addMethod("phoneOrEmail", function(value, element) {
return this.optional(element) ||
($.validator.methods["phonesUK"].call(this, value, element)) ||
($.validator.methods["email"].call(this, value, element));
}, "Please enter a valid phone number or email address");
//apply it to my page
$(document).on("pagecreate", function () {
// validate new number form
$("#addNumber").validate({
errorPlacement: function(error, element) {
error.insertAfter(element.parent()); // <- make sure the error message appears after parent element (after textbox!)
},
rules: {
phoneNumber:
{
phoneOrEmail: true,
required: true,
}
},
messages: {
phoneNumber: "Please enter a valid phone number or email address",
},
//check if valid - post if is
submitHandler: function(form) {
$('#PopUpAddNumber').popup('close');
$.post("customer_AddNewNumber.php", $("#addNumber").serialize(), function(response)
{
LoadCustomerNumber();
});
}
}); //end validate
//reset form after validate
$('#addNumberReset').click(function () {
$('#addNumber').validate().resetForm();
});
}); // end function

bind kendo.data.DataSource to combo using MVVM

Again next question , this time a tricky one,
Datasource:
var dsCountryList =
new kendo.data.DataSource({
transport: {
read: {
dataType: "jsonp",
url: "/Masters/GetCountries"
}
},
schema: {
model: {
id: "CountryID",
fields: {
"CountryDesc": {
}
}
}
}
});
Observable object
function Set_MVVMSupplier() {
vmSupplier = kendo.observable({
SupplierID: 0,
SupplierName: "",
AccountNo: "",
CountryList: dsCountryList,
});
kendo.bind($("#supplierForm"), vmSupplier);
}
here is the html which is bind to observable object , but i am not getting combobox filled, also each time i clicked the combo request goes to server and bring data in json format for countryID, CountryDesc
<div class="span6">
<div class="control-group">
<label class="control-label" for="txtCountryId">Country</label>
<div class="row-fluid controls">
#*<input class="input-large" type="text" id="txtCountryId" placeholder="CountryId" data-bind="value: CountryId">*#
<select id="txtCountryId" data-role="dropdownlist"
data-text-field="CountryDesc" data-value-field="CountryID" , data-skip="true"
data-bind="source: CountryList, value: CountryDesc">
</select>
</div>
</div>
</div>
I didn't get the answer , so i found an alternate working ice of code. just have a look and if it helps then please vote.
created model for ddl in js file
ddl = kendo.data.Model.define({
fields: {
CountryId: { type: "int" },
ConfigurationID: { type: "int" }
}
});
added var ddl to MVVM js file
vmSupplier = kendo.observable({
CountryId: new ddl({ CountryId: 0 }),
ConfigurationID: new ddl({ ConfigurationID: 0 }),});
added code in controller
using (CountriesManager objCountriesManager = new CountriesManager())
{
ViewBag.Countries = new SelectList(
objCountriesManager.GetCountries().Select(p => new { p.CountryID, p.CountryDesc })
, "CountryID", "CountryDesc"); ;
}
added code in cshtml
<div class="span4">
<label class="control-label" for="txtCountryId">Country</label>
#Html.DropDownList("Countries", null,
new System.Collections.Generic.Dictionary<string, object> {
{"id", "txtCountryId" },
{ "data-bind","value: CountryId"} })
</div>
this way i got solved the problem

Knockout with ASP.NET MVC4

Looking to start using Knockout with ASP.NET MVC4. Have watch some examples and encountered the following questions.
Today I write my view models backend, I can totally replace it
with knockout view models on the client side?
Is there anything like DataAnnotations in Knockout for
validation?
Yes, you remove the server view and view models. All are now are now on the client.
See Knockout validation
Also, you may want to check out OData/WCF data services (http://blogs.msdn.com/b/astoriateam/). It basically gives you a Model and Controller. With this approach you server ends up only serving static HTML pages and Model data as AJAX calls. And it also supports "paging" of data.
IMHO, this the way of the future.
Other links of interest:
Authorisation - http://msdn.microsoft.com/en-us/library/dd728284.aspx
Routing - http://blogs.msdn.com/b/rjacobs/archive/2010/04/05/using-system-web-routing-with-data-services-odata.aspx or http://code.msdn.microsoft.com/WCF-Data-Service-with-285746ac
Knockout.js is a great library. But if you ask people what to use knockout or angular.
Most of them will tell you Angular.js is better, though they are very similar.
I use knockout in my projects. And there are many things that can simplify your development.
For example. I use server side validation only. When user clicks on "submit", my javascript collects model and sends it to controller (asyncronously AJAX). Controller has validation, and if validation fails the response would be HTTP:500 and body will be validation result structure, that displays all errors in correct places in HTML.
From user's perspective it seems like client-side validation.
You can see how it works in this example: Create Order Example (Upida.Net).
You can use this library or this
or use this samole
<script id="customMessageTemplate" type="text/html">
<em class="customMessage" data-bind='validationMessage: field'></em>
</script>
<fieldset>
<legend>User: <span data-bind='text: errors().length'></span> errors</legend>
<label>First name: <input data-bind='value: firstName'/></label>
<label>Last name: <input data-bind='value: lastName'/></label>
<div data-bind='validationOptions: { messageTemplate: "customMessageTemplate" }'>
<label>Email: <input data-bind='value: emailAddress' required pattern="#"/></label>
<label>Location: <input data-bind='value: location'/></label>
<label>Age: <input data-bind='value: age' required/></label>
</div>
<label>
Subscriptions:
<select data-bind='value: subscription, options: subscriptionOptions, optionsCaption: "Choose one..."'></select>
</label>
<label>Password: <input data-bind='value: password' type="password"/></label>
<label>Retype password: <input data-bind='value: confirmPassword' type="password"/></label>
<label>10 + 1 = <input data-bind='value: captcha'/></label>
</fieldset>
<button type="button" data-bind='click: submit'>Submit</button>
<br />
<br />
<button type="button" data-bind='click: requireLocation'>Make 'Location' required</button>
ko.validation.rules.pattern.message = 'Invalid.';
ko.validation.configure({
registerExtenders: true,
messagesOnModified: true,
insertMessages: true,
parseInputAttributes: true,
messageTemplate: null
});
var captcha = function (val) {
return val == 11;
};
var mustEqual = function (val, other) {
return val == other();
};
var viewModel = {
firstName: ko.observable().extend({ minLength: 2, maxLength: 10 }),
lastName: ko.observable().extend({ required: true }),
emailAddress: ko.observable().extend({ // custom message
required: { message: 'Please supply your email address.' }
}),
age: ko.observable().extend({ min: 1, max: 100 }),
location: ko.observable(),
subscriptionOptions: ['Technology', 'Music'],
subscription: ko.observable().extend({ required: true }),
password: ko.observable(),
captcha: ko.observable().extend({ // custom validator
validation: { validator: captcha, message: 'Please check.' }
}),
submit: function () {
if (viewModel.errors().length == 0) {
alert('Thank you.');
} else {
alert('Please check your submission.');
viewModel.errors.showAllMessages();
}
}
};
viewModel.confirmPassword = ko.observable().extend({
validation: { validator: mustEqual, message: 'Passwords do not match.', params: viewModel.password }
}),
viewModel.errors = ko.validation.group(viewModel);
viewModel.requireLocation = function () {
viewModel.location.extend({ required: true });
};
ko.applyBindings(viewModel);

Resources