I have a view controller that is returning ViewComponent which returns a View (.cshtml) containing everthing I need.
In another view I want to use that, so i make ajax call to the controller to get raw html in the response.
Modal
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-
dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data
dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JS:
$.ajax({
url: 'getModal/blabla',
type: 'GET',
data: {
Id: id
},
success: function (data) {
$('#myModal').modal('show').html(data);
},
error: function (error) {
console.error(error);
},
});
In my ViewComponent I return View like this:
return View("~/Views/MyModal.cshtml", new MyViewModel()
{
Id = obj.id
});
Here is a demo:
TestViewComponent.cshtml(you want to pass data to controller,so you need to use type: 'POST' in ajax):
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-
dismiss="modal">
×
</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data
dismiss="modal">
Close
</button>
</div>
</div>
</div>
</div>
#section scripts{
<script>
$(function () {
var Id = 1;
$.ajax({
url: '/Test1/RetunSample1ViewComponent',
type: 'POST',
data: {
Id: Id
},
success: function (data) {
$('#myModal').modal('show').html(data);
},
error: function (error) {
console.error(error);
},
});
})
</script>
}
Controller:
public IActionResult TestViewComponent() {
return View();
}
public IActionResult RetunSample1ViewComponent(int Id) {
return ViewComponent("Sample1", new Sample1Model { Id = Id , Name="sample1"}); ;
}
ViewComponents/Sample1:
public class Sample1:ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(Sample1Model s)
{
return View("~/Views/Shared/Default.cshtml",s);
}
}
Views/Shared/Default.cshtml:
#model Sample1Model
Id:<input asp-for="Id" />
Name:<input asp-for="Name" />
result:
You can also use partial view:
Controller:
public IActionResult ReturnPartialView(int Id) {
return PartialView("~/Views/Shared/Default.cshtml", new Sample1Model { Id = Id, Name = "sample1" });
}
View:
$(function () {
var Id = 1;
$.ajax({
url: '/Test1/ReturnPartialView',
type: 'POST',
data: {
Id: Id
},
success: function (data) {
$('#myModal').modal('show').html(data);
},
error: function (error) {
console.error(error);
},
});
})
Related
This is the index file code:
public IList<Employee> Employee { get; set; }
public async Task OnGetAsync()
{
Employee = await _context.Employee.ToListAsync();
}
public JsonResult EmployeeList()
{
var data = _context.Employee.ToList();
return new JsonResult(data);
}
[HttpPost]
public JsonResult AddEmployee(Employee e)
{
var emp = new Employee()
{
Name = e.Name,
Age = e.Age,
Email = e.Email
};
_context.Employee.Add(emp);
_context.SaveChanges();
return new JsonResult("Success!!!");
}
Button to open Modal:
<button class="btn btn-info mb-3" id="btn1">Add Employee</button>
The Modal:
<!-- The Modal -->
<div class="modal Add-Emp">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Add Employee</h4>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<!-- Modal body -->
<div class="modal-body">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label>Name</label>
<input type="text" placeholder="Enter Name" class="form-control" id="Name" autocomplete="off"/>
</div>
<div class="form-group">
<label>Age</label>
<input type="text" placeholder="Enter Age" class="form-control" id="Age" autocomplete="off"/>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" placeholder="Enter Email" class="form-control" id="Email" autocomplete="off"/>
</div>
</form>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button class="btn btn-primary" onclick="AddEmployee();">Save</button> I
<button class="btn btn-danger btn-default" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The Js Code:
$("#btn1").click(function () {
$(".Add-Emp").modal("show")
})
function AddEmployee() { debugger
var objData = { Name: $("#Name").val(), Age: $("#Age").val(), Email: $("#Email").val() }
$.ajax({
url: "Pages/Employees/Index/AddEmployee",
type: "Post",
data: objData,
contentType: "application/xxx-www-form-url-encoded; charset=utf-8",
dataType: "json",
success: function () { alert("Data Saved"); },
error: function () { alert("Error!!!"); }
})
}
Modal opens on click But data does not get posted on clicking the save button it displays alert "Error!!!" defined in failure of ajax requestㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ
1.You maybe not familiar with Razor Pages, Razor pages uses OnGet and OnPost to deal with the Http Get and Post request. If you need another Get or Post method in current PageModel, you need define the method name like: OnGetHandlerName or OnPostHandlerName.
2.If your .cshtml.cs file located like: Pages/Employees/Index.cshtml.cs, the request url should be:/Employees/Index. If you set the handler in your PageModel, the request url should be:/Employees/Index?handler=xxx.
3.For how to use Ajax in Razor Pages, Razor Pages enable anti-forgery token validation by default, so you need add this token to header in ajax.
If you use form in Razor Pages, it will default generate an input with token. If not, you need add #Html.AntiForgeryToken() manually.
A whole working demo you could follow:
Page(Pages/Employees/Index.cshtml):
#page
#model IndexModel
<button class="btn btn-info mb-3" id="btn1">Add Employee</button>
<div class="modal Add-Emp">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Add Employee</h4>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<!-- Modal body -->
<div class="modal-body">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label>Name</label>
<input type="text" placeholder="Enter Name" class="form-control" id="Name" autocomplete="off" />
</div>
<div class="form-group">
<label>Age</label>
<input type="text" placeholder="Enter Age" class="form-control" id="Age" autocomplete="off" />
</div>
<div class="form-group">
<label>Email</label>
<input type="text" placeholder="Enter Email" class="form-control" id="Email" autocomplete="off" />
</div>
</form>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button class="btn btn-primary" onclick="AddEmployee();">Save</button> I
<button class="btn btn-danger btn-default" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#section Scripts
{
<script>
$("#btn1").click(function () {
$(".Add-Emp").modal("show")
})
function AddEmployee() {
debugger
var objData = { Name: $("#Name").val(), Age: $("#Age").val(), Email: $("#Email").val() }
$.ajax({
url: "/Employees/Index?handler=AddEmployee",
type: "Post",
data: JSON.stringify(objData), //change here...
contentType: "application/json; charset=utf-8", //change here...
headers: {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
}, //add this....
dataType: "json",
success: function () { alert("Data Saved"); },
error: function () { alert("Error!!!"); }
})
}
</script>
}
Pages/Employees/Index.cshtml.cs:
public class IndexModel : PageModel
{
//...
public IList<Employee> Employee { get; set; }
public async Task OnGetAsync()
{
Employee = await _context.Employee.ToListAsync();
}
public JsonResult OnGetEmployeeList()
{
var data = _context.Employee.ToList();
return new JsonResult(data);
}
public JsonResult OnPostAddEmployee([FromBody]Employee e)
{
var emp = new Employee()
{
Name = e.Name,
Age = e.Age,
Email = e.Email
};
return new JsonResult("Success!!!");
}
}
I have select element inside a modal form configured as single selection, I load my data using ajax call. The problem is when I select item1 then hide the modal, when I show the modal again and select item1 again the select field text becomes empty.
First selection:
Second selection:
I tried logging the value and selected object changed.
First selection logged value:
Second selection logged value:
So basically the selected object is changed on the second selection. I tried re-initializing my select2 but still the problem persist. I also checked the response json on my second selection and the content is correct.
my html code:
<div class="modal fade" id="my-modal" tabindex="-1" role="dialog" aria-labelledby="modal-title" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<form class="w-100" id="my-form">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modal-title" >Modal</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
</button>
</div>
<div class="modal-body">
<div class="form-group">
<div class="d-flex w-100">
<div class="w-50 d-flex flex-column pr-1">
<div class="d-flex">
<select id="my-select" class="form-control" data-style="select-with-transition">
<option></option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
my javascript code:
$('#my-modal').on('shown.bs.modal', function () {
$('#my-select').select2({
placeholder: "select item",
allowClear: true,
dropdownParent: $('#my-modal'),
ajax: {
url: "/my-url",
dataType: "json",
delay: 250,
data: function(param) {
return {
search: param.term
}
},
processResults: function(data) {
return {
results: data.items
};
},
cache: true
},
escapeMarkup: function(e) {
return e
},
minimumInputLength: 1,
templateResult: function(repo) {
if (repo.loading) {
return repo.text;
}
return `<option value="${repo.id}">${repo.name}</option>`
},
templateSelection: function(item) {
console.log(item);
return item.name
}
});
});
I want to know, how to hide below shown Bootstrap modal form, after submitting the value to the service. I have tried with commented code, but didn't help me. Is there any alternatives.?
settings.component.ts
import { Component, OnInit} from '#angular/core';
import { CategoryVM } from '../view-models/category';
import { AppDataService } from '../services/app-data.service';
import { NgForm } from '#angular/forms';
import { FormControl, FormGroup, Validators } from '#angular/forms';
import { Location } from '#angular/common';
//declare var $: any;
#Component({
selector: 'app-settings',
templateUrl: './settings.component.html',
styleUrls: ['./settings.component.css']
})
export class SettingsComponent implements OnInit {
categories: CategoryVM[] = [];
form: FormGroup;
errorMessage: string;
//visible: boolean;
//private visibleAnimate = false;
// public visible = true;
constructor(private dataService: AppDataService, private location: Location) {
dataService.getCountries().subscribe((data) => this.categories = data);
}
ngOnInit() {
this.dataService.vm = { ParentId: 0, Name: "" };
// this.visible = true;
}
onBack() {
this.errorMessage = null;
this.location.back();
}
onCancel() {
this.onBack();
}
onSubmit(form: NgForm) {
this.dataService.createCategory(form.value)
.subscribe(data => {
alert("Value Added Successfully");
//$("#myModal").hide();
//$("#myModal").modal("hide");
// this.visible = false;
this.categories.push(data);
//document.getElementById("openModalButton").click();
});
}
}
Please focus in OnSubmit() event of form in above and Below is the template
settings.component.html
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">start here</button>
<!--<button id="openModalButton" [hidden]="true" type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">start here</button>-->
<div id="myModal" class="modal fade" role="dialog">
<!--<div id="myModal" class="modal fade" role="dialog" *ngIf="visible">-->
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Login</h4>
</div>
<div class="modal-body">
<form class="cat-form" #categoryForm="ngForm" (ngSubmit)="onSubmit(categoryForm)">
<!--<form class="cat-form" #categoryForm="ngForm" (ngSubmit)="onSubmit(categoryForm);visible=false;">-->
<label>Name</label>
<div class="form-group">
<input class="form-control" name="Name" placeholder="Name" #Name="ngModel" [(ngModel)]="dataService.vm.Name">
</div>
<div class="form-row">
<div class="form-group col-md-8">
<button type="submit" class="btn btn-lg btn-block btn-primary">Create</button>
</div>
<div class="form-group col-md-4">
<button type="button" class="btn btn-lg btn-block" (click)="onCancel()" data-dismiss="modal">Cancel</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
If I use commented line of code Modal-form will hide, but opacity remains as shown in this image
Your commented code is a jQuery code, so I assume you don't use an Angular Framework (like ng-bootstrap for example).
You should have a look and integrate one of the abstraction of Bootstrap.
Use jQuery in your component means you manipulate directly the dom and this is really not the good way to do.
https://ng-bootstrap.github.io/
https://github.com/valor-software/ngx-bootstrap
I am using a bootstrap model to create and update groups. on the backend side, there are no issues. Below I have my ts and HTML code I used. the modal works fine, but I don't know how to return any values from my form to my ts file so i can use it in an API call.
also for an image I need formdata
in short:
What's the issue: Returning user inputs(+image) in angular 2
!edit! the error i get is:
_co.save is not a function
html:
<app-modal #modal>
<div class="app-modal-header">
header
</div>
<div class="app-modal-body">
<form #modalform="ngForm" (ngSubmit)="save(modalform.value)" >
First name: <input type="text" name="FirstName" ngModel><br>
Last name: <input type="text" name="LastName" ngModel><br>
image: <input type="file" name="image" ngModel><br>
</form>
</div>
<div class="app-modal-footer">
<button type="button" class="btn btn-default" (click)="modal.hide()">Close</button>
<button type="button" class="btn btn-primary" (click)="modal.hide()">Save changes</button>
</div>
</app-modal>
TS:
#Component({
selector: 'app-modal',
template: `
<div (click)="onContainerClicked($event)" class="modal fade" tabindex="-1" [ngClass]="{'in': visibleAnimate}"
[ngStyle]="{'display': visible ? 'block' : 'none', 'opacity': visibleAnimate ? 1 : 0}" style=" background: rgba(0,0,0,0.6);">
<div class="modal-dialog" style="padding-top: 25%;">
<div class="modal-content">
<div class="modal-header">
<ng-content select=".app-modal-header"></ng-content>
</div>
<div class="modal-body">
<ng-content select=".app-modal-body"></ng-content>
</div>
<div class="modal-footer">
<ng-content select=".app-modal-footer"></ng-content>
</div>
</div>
</div>
</div>
`
})
export class ModalComponent {
public visible = false;
public visibleAnimate = false;
public show(): void {
this.visible = true;
setTimeout(() => this.visibleAnimate = true, 100);
}
public save(): void{
}
public hide(): void {
this.visibleAnimate = false;
setTimeout(() => this.visible = false, 300);
}
public onContainerClicked(event: MouseEvent): void {
if ((<HTMLElement>event.target).classList.contains('modal')) {
this.hide();
}
}
}
fixed it by placing the save function in the other component
I'm using Bootstrap to display my modal in my webpage. My data is stored in database. I used ng-repeat to get my array data from database. I want to pass my room.room_name into modal. How can I do that?
HTML:
<tr data-ng-repeat="room in data">
<td>{{room.room_id}}</td>
<td>{{room.room_name}}</td>
<td>{{room.max_pax}}</td>
<td>{{room.no_booked}}</td>
<td>
<button class="btn btn-warning" data-toggle="modal" data-target="#editRoom"></button>
<button class="btn btn-danger" data-ng-click="delRoom(room.room_id)"></button>
</td>
</tr>
My Modal:
I want to pass room_room.name value and insert into input text value.
I tried to use ng-value but failed.
<div id="editRoom" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit Library Discussion Room</h4>
</div>
<div class="modal-body">
<form>
<label for="editName">Room Name: </label>
<input type="text" name="editName" data-ng-model="room.name" id="editName" data-ng-value="{{room.room_name}}" />
<br />
<label for="editMaxPax">Maximum Person: </label>
<input type="text" name="editMaxPax" data-ng-model="room.maxPax" id="editMaxPax" value="room.max_pax" />
<button type="submit" class="btn btn-default" data-ng-click="editRoom(room)">Edit</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
AngularJS (Controller):
My get the value from database and store it into array named "data".
var app = angular.module("myApp", ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
"use strict";
$routeProvider
.when("/", {
templateUrl: "facilities.html"
});
}]);
app.controller("myCtrl", function ($scope, $http) {
"use strict";
$scope.state = "";
$scope.addRoom = function (room) {
$http.post("add_library_room.php", {'room_name': room.name, 'max_pax': room.maxPax})
.then(function () {
$scope.msg = "Room is inserted into database.";
});
};
$scope.displayRoom = function () {
$http.get("view_library_room.php")
.then(function (response) {
var data = response.data;
$scope.data = data;
console.log(data);
});
};
$scope.delRoom = function (roomID) {
$http.post("del_library_room.php", {'room_id': roomID})
.then(function () {
$scope.msg = "Room is deleted successfully.";
});
};
$scope.footer = function (page) {
if (page === "login") {
$scope.state = page;
} else {
$scope.state = "";
}
return $scope.state;
};
});