DropDownListFor Unexpected token u - javascript

I'm getting a very annoying error
Uncaught SyntaxError: Unexpected token u
I have multiple drop down lists, I'm using #Html.DropDownListFor() helper to render it. The error occur as follows:
1- Open one of the drop down list and select an item
2- Open another drop down list then select an item
On step 2 I got the error message but I can't find any thing suspicious or wrong in my code.
Here is how I fill the drop down lists with data (all drop down lists take the same data):
using (Entities context = new Entities())
{
ISDCodes = context.ISDCodes.ToList();
}
ViewBag.ISDCodes = new SelectList(ISDCodes, "ID", typeTextFieldForISDCode);
ISDCode Model:
public partial class ISDCode
{
public int ID { get; set; }
public string CodeEN { get; set; }
public string CodeAR { get; set; }
public string Country { get; set; }
public string PhoneCode { get; set; }
public string Code { get; set; }
}
Here is the Html razor view for these drop down lists:
<div class="form-group clearfix">
<label class="col-sm-2 col-sm-offset-2 control-label">
#Html.LabelFor(model => model.Phone1)
<span class="required">*</span>
</label>
<div class="col-sm-2">
#Html.DropDownListFor(x => x.ISDIDForPhone1, ViewBag.ISDCodes as SelectList, Infas.KFAS.Web.Resources.KFASResources.SelectISDCode,new { id = "ISDIDForPhone1", #class = "form-control" })
</div>
<div class="col-sm-4">
#Html.TextBoxFor(model => model.Phone1, new { #class = "form-control", #maxlength = "12", #onkeypress = "keypress(event)", #type = "number" })
#Html.ValidationMessageFor(model => model.Phone1)
</div>
</div>
<div class="form-group clearfix">
<label class="col-sm-2 col-sm-offset-2 control-label">
#Html.LabelFor(model => model.Phone2)
</label>
<div class="col-sm-2">
#Html.DropDownListFor(x => x.ISDIDForPhone2, ViewBag.ISDCodes as SelectList, Infas.KFAS.Web.Resources.KFASResources.SelectISDCode,new { id = "ISDIDForPhone2", #class = "form-control" })
</div>
<div class="col-sm-4">
#Html.TextBoxFor(model => model.Phone2, new { #class = "form-control", #maxlength = "12", #onkeypress = "keypress(event)", #type = "number" })
#Html.ValidationMessageFor(model => model.Phone2)
</div>
</div>

Related

How do I stop Angular from automatically alphabetizing object keys?

I have this array...
public incidents: any[] = [
{
id: 1,
name: "Default Case Set",
type: "CASEWORK",
str: 34,
mtdna: 0,
ystr: 0,
xstr: 0,
snps: 0
}
]
I'm passing it into a modal like this...
public openEditModal(id: number): void {
this.incidentToBeEdited = this.incidents.filter(result => result.id == id).pop();
const initialState: ModalOptions = {
initialState: {
items: this.incidentToBeEdited,
title: 'Edit Incident'
}
};
// Close modal
this.bsModalRef = this.modalService.show(EditModalComponent, initialState);
}
The problem is that the keys in the object in the incidents array are automatically alphabetized.
When I console the "this.incidentToBeEdited" variable, I get this...
{
mtdna: 0
name: "Default Case Set"
snps: 0
str: 34
type: "CASEWORK"
xstr: 0
ystr: 0
}
So the object that gets sent to the modal (for display purposes) is automatically alphabetized.
I don't want this because I want the fields to appear as they do in the table, which is how they are in the original incidents array.
Is there anyway I can override Angular's need to alphabetize an object?
Here is the code for EditModalComponent...
export class EditModalComponent implements OnInit {
constructor(
public bsModalRef: BsModalRef,
private http: HttpClient,
private formBuilder: FormBuilder) {
this.items = this.items;
this.bsModalRef = this.bsModalRef;
this.editModal = this.formBuilder.group({});
}
// Page loading properties
public httpRequestInProgress: boolean = false;
public pageLoaded: boolean = false;
public pageLoadError: string = '';
public pageLoading: boolean = true;
// Properties
public editModal: FormGroup;
public items?: any;
public title?: string;
// Methods
ngOnInit(): void {
this.editModal = this.formBuilder.group(
this.items
)
console.log("this.items", this.items);
// Remove id from list of items
const itemsInAnArray = [this.items];
itemsInAnArray.forEach((item: any) => delete item.id);
this.pageLoading = false;
this.pageLoaded = true;
}
}
Here is the HTML for EditModalComponent...
<form [formGroup]="editModal" *ngIf="this.items">
<div class="row">
<div class="col-sm-12">
<div *ngFor="let item of this.items | keyvalue">
<div class="col-sm-12 mb-3">
<label class="text-capitalize" for="firstName">{{item.key}}</label>
<input class="form-control"
id="{{item.key}}"
value="{{item.value}}"
formControlName="{{item.key}}">
</div>
</div>
</div>
<div class="mt-3">
<button class="btn btn-primary float-start"
type="button"
(click)="saveAsync()">
Save
</button>
<button class="btn btn-secondary me-1 float-start"
type="button"
(click)="bsModalRef.hide()">
Cancel
</button>
</div>
</div>
</form>
```

How to access the properties of a formArray in HTML?

I'm trying to implement a reactive Angular form, but, I can't access the properties of the array on HTML, I never worked with reactive form, if anyone could guide me I would be grateful! I'm using Angular 10 and I have the following code:
TS
operationModel: IScriptOperationsModel;
formOperation: FormGroup;
constructor(
private fb: FormBuilder,
...
) {}
ngOnInit() {
this.operationModel = new IScriptOperationsModel();
this.operationModel.scriptOperationOrders = [];
this.buildForm(new IScriptOperationsModel());
this.scriptOperationsService.findScriptOperation(this.operationId).subscribe((operation) => {
this.operationModel = operation.data as IScriptOperationsModel; // api return
this.buildForm(this.operationModel); // I pass the return of the api to the form
});
}
buildForm(operation: IScriptOperationsModel) {
this.formOperation = this.fb.group({
descriptionCode: [operation.descriptionCode],
description: [operation.description],
workStations: this.fb.array([])
});
this.formOperation.setControl('workStations', this.fb.array(this.operationModel.scriptOperationOrders));
}
get workStations(): FormArray {
return this.formOperation.get('workStations') as FormArray;
}
HTML
<div
class="card"
[ngClass]="{'bg-principal': idx === 0, 'bg-alternative': idx !== 0}"
formArrayName="workStations"
*ngFor="let workstation of workStations.controls; index as idx"
>
<div class="card-body" [formGroupName]="idx">
<div class="form-row">
<div class="form-group col-md-1">
<label>Id Oper.</label>
<input
type="text"
name="idOperation"
class="form-control"
disabled
formControlName="rank" <!-- whatever with or without binding gives error -->
/>
</div>
<div class="form-group col-md-2">
<label>Time</label>
<input
type="time" class="form-control" name="defaultTime"
[formControlName]="defaultTime" <!-- whatever with or without binding gives error -->
/>
</div>
</div>
</div>
</div>
Models
export class IScriptOperationsModel extends Serializable {
public description: string;
public descriptionCode: string;
public scriptOperationOrders: IScriptOperationOrdersModel[]; // array which I need
}
export class IScriptOperationOrdersModel extends Serializable {
public rank: number;
public defaultTime: string;
public asset?: IAssetModel;
public provider?: IProviderModel;
}
error-handler.service.ts:87 Error: Cannot find control with path: 'workStations -> 0 -> rank' # undefined:undefined
NOTE: I already looked at some answers here on the site such as this, this and this , but none of them solved this problem!
your problem is here :
this.formOperation.setControl(
'workStations',
this.fb.array(this.operationModel.scriptOperationOrders) <== here the problem
);
you are passing an array of IScriptOperationOrdersModel instead of array of form group.
To make your code working, you have to loop on every element of this.operationModel.scriptOperationOrders array , and instanciate a new FormControl object then push it in the workStations form array.
To access its elements, you can use controls[indexOfGroup].rate
You can take a look at this simple example you will understand everything.

Laravel Eloquent Many to Many Search with Ajax

I had this question last week. I found the solution to add and remove related models. But this time i want to make a search.
Database
drugs table
Schema::create('drugs', function (Blueprint $table) {
$table->BigIncrements('id')->unique();
$table->string('name')->unique();
$table->mediumText('info');
$table->timestamps();
});
interactions table
Schema::create('interactions', function (Blueprint $table) {
$table->BigIncrements('id');
$table->string('name');
$table->string('description');
$table->string('category');
$table->timestamps();
});
drug_interaction table
Schema::create('drug_interaction', function (Blueprint $table) {
$table->integer('interaction_id')->unsigned();
$table->foreign('interaction_id')->references('id')->on('interactions');
$table->integer('drug_id')->unsigned();
$table->foreign('drug_id')->references('id')->on('drugs');
$table->timestamps();
});
Models
Drug
class Drug extends Model
{
//Table Name
protected $table = 'drugs';
//Primary Key
public $primaryKey = 'id';
//Timestamps
public $timestamps = true;
public function interactions()
{
return $this->belongsToMany(Interaction::class);
}
}
Interaction
class Interaction extends Model
{
//Table Name
protected $table = 'interactions';
//Primary Key
public $primaryKey = 'id';
//Timestamps
public $timestamps = true;
//Relationship
public function drugs()
{
return $this->belongsToMany(Drug::class);
}
}
InteractionsController
Since edit/update function works properly and kinda' a part of what i look for, i am only adding the update function of conrtoller.
public function update(Request $request, Interaction $interaction)
{
$interaction->name = $request->name;
$interaction->description = $request->description;
$interaction->category = $request->category;
$interaction->save();
$interaction->drugs()->sync($request->drugs);
return redirect('/interactions')->with('success', 'Interaction Updated');
}
The Form to Add Drugs to Interactions
<div class="container">
<div class="row">
<div class="col-md-12">
{!! Form::open(['url' => 'interactions/' . $interaction->id, 'method' => 'patch']) !!}
<div class="form-group">
{{Form::label('name', 'Etkileşim İsmi')}}
{{Form::text('name', $interaction->name, ['class' => 'form-control', 'placeholder' => 'Etkileşim İsmi'])}}
</div>
<div class="form-group">
{{Form::label('description', 'Etkileşim Açıklaması')}}
{{Form::textarea('description', $interaction->description, ['class' => 'form-control', 'placeholder' => 'Etkileşim Bilgisi'])}}
</div>
<div class="form-group">
{{Form::label('category', 'Kategori')}}
{{Form::text('category', $interaction->category, ['class' => 'form-control', 'placeholder' => 'Etkileşim Kategorisi'])}}
</div>
<div class="form-group">
{!! Form::label('İlaçları Seçin') !!}
{!! Form::select('drugs[]', $drugs, null, ['multiple' => 'multiple', 'class' => 'form-control drugs']) !!}
</div>
{{Form::submit('Güncelle', ['class'=>'btn btn-primary'])}}
{!! Form::close() !!}
</div>
</div>
</div>
select2.js
$(document).ready(function() {
$('.drugs').select2({
minimumResultsForSearch: '25',
minimumInputLength: '3',
placeholder: "Etkileşimi olan 2 İlacı Seçiniz."
});
});
SearchController
class SearchController extends Controller
{
public function index()
{
$drugs = Drug::pluck('name','id');
}
I also have the form i used on interaction/create.blade on search.blade:
<div class="col-md-12">
{!! Form::open(['url' => 'getInteraction', 'method' => 'get']) !!}
<div class="form-group">
{!! Form::label('İlaçları Seçin') !!}
{!! Form::select('drugs[]', $drugs, null, ['multiple' => 'multiple', 'class' => 'form-control drugs', 'type' => 'hidden']) !!}
</div>
{!! Form::submit('Ara', ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}
I couldn't build a query to search the "related interactions" for each selected "drug" , array those interactions and print them only if an interaction_id exists twice in array.
All help is appreciated. Thanks All !

Check if two fields already have an exact match when submitting data to a database with bootstrap?

I am making an extremely simple app that is for our department's weekly college football pickem. We pick one game per weekend, then place bets on who will win and what the total combined score will be. We needed a spot to do this without seeing everyone elses predictions, as that gives late participators a huge advantage.
I already have a simple html page and local db that displays DB entries, showing the employee name and the date submitted. When creating an entry, you enter your name, prediction of the winner, the combined total score, and the date. It doesn't display the predictions details until Fridays at 2PM, while also locking any new submissions, so that no one can base their predictions off of what everyone else has.
My problem is I'm trying to make it check to make sure that someone else doesn't have the exact same Winner+Score combo when clicking submit on the create page. Somehow it just needs to scan those two DB attributes to make sure no one else has the exact same value for those. There's usually only going to be around 10 people participating. Here is my code for the create page.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Pick</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.winner, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.winner, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.winner, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.points, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.points, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.points, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.postDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.postDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.postDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
I just need the submit button to tell them that they can't submit those values, or either just disable it until they have values that aren't an exact match.
What about sending it on controller and check values here, then you can put if condition and check values, if they matches, redirect back with message, which you can store for example in:
ViewData["Message"] = "Your message";
And then use data:
<h3>Passing Data From Controller to View using ViewBag</h3>
#{
var data = ViewBag.Message;
}
<h3>Id: #data.Id</h3>
<h3>RecordName: #data.RecordName</h3>
<h3>RecordDetail: #data.RecordDetail</h3>
Example webpage:
https://www.c-sharpcorner.com/article/asp-net-mvc-passing-data-from-controller-to-view/

Partial view not getting validated after button click when dynamically loaded using jQuery get

I am using MVC4 to create a project and in that project I am using jQuery dialog to show pop up to user to edit the data.
When user click on Edit action link it shows a pop up which contains form to edit values of the user.
Edit
This is my code for showing pop up to user.
$('.edit').click(function () {
$.get($(this).data('url'), function (data) {
$('#dialogEdit').dialog({
modal: true,
autoResize: true,
resizable: true,
position: {
my: "center top",
at: "center top",
of: window
},
autoOpen: true,
bgiframe: true,
open: function () {
document.getElementById('dialogEdit').innerHTML = data;
},
close: function () {
document.getElementById('dialogEdit').innerHTML = "";
document.getElementById('dialogEdit').innerText = "";
$("#dialogEdit").empty().hide();
}
});
});
});
This is partial view
#model PITCRoster.ViewModel.LookupTblUserViewModel
#using (Html.BeginForm("SaveChangesResources", "Resources"))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
Html.RenderPartial("_CreateNewResource", Model.tblUser);
Html.RenderPartial("_LookUpDropDowns", Model.LookUpViewModel);
<br />
<input type="submit" value="Save"/>
}
_CreateNewResource.cshtml
#model PITCRoster.tblUser
<fieldset>
<legend>tblUser</legend>
<div class="editor-label">
#Html.LabelFor(model => model.UserId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
</fieldset>
_lookupDropDowns.cshtml
#model PITCRoster.ViewModel.LookUpViewModel
#Html.LabelFor(model => model.SelectedLocation)
#Html.DropDownListFor(m => m.SelectedLocation, Model.LocationList, "-Please select-")
#Html.ValidationMessageFor(m => m.SelectedLocation)
#Html.LabelFor(m => m.SelectedStream)
#Html.DropDownListFor(m => m.SelectedStream, Model.StreamList, "-Please select-")
#Html.ValidationMessageFor(m => m.SelectedStream)
#Html.LabelFor(m => m.SelectedDepartment)
#Html.DropDownListFor(m => m.SelectedDepartment, Model.DepartmentList, "-Please select-")
#Html.ValidationMessageFor(m => m.SelectedDepartment)
#Html.LabelFor(m => m.SelectedGlobalLocation)
#Html.DropDownListFor(m => m.SelectedGlobalLocation, Model.GlobalLocationList, "-Please select-")
#Html.ValidationMessageFor(m => m.SelectedGlobalLocation)
I tried using
$('form').removeData('validator');
$('form').removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('form');
and some more options which were on SO but it didn't help me solve problem.
Can you please help me with this?
Thank you ^_^
You need to ensure that you re-parse the validator after the new content is added to the DOM
$('.edit').click(function () {
$.get($(this).data('url'), function (data) {
$('#dialogEdit').dialog({
....
open: function () {
document.getElementById('dialogEdit').innerHTML = data;
// reparse the validator here
var form = $('form');
form.data('validator', null);
$.validator.unobtrusive.parse(form);
},
....
});
});
});

Categories

Resources