Exception handling using the modal - asp.net

There was such task.
I have a controller method of removing
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
try {
TechnologicalCard technologicalCard = db.TechnologicalCards.Find(id);
db.TechnologicalCards.Remove(technologicalCard);
db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception ex)
{
ViewBag.Error = true;
TempData["message"] = "someMessage";
return RedirectToAction("Index");
}
}
How can I do that would be when an exception is thrown during the removal of the modal appeared with warning text ?
UPDATE
I added the index method
public ActionResult Index()
{
var id_Head = User.Identity.GetUserId();
TempData["message"] = "someMessage";
var technologicalCards = db.TechnologicalCards.Where(c => c.IdHeadDepartment == id_Head).ToList();
return View(technologicalCards);
}
My view has contains the following code
#model IEnumerable<AccountingPlusProject.Models.TechnologicalCard>
#{
ViewBag.Title = "Учёт+";
}
<style>
.md-form {
position: relative;
top: 40px;
width: 20%;
height: 20%;
text-align: center;
}
.img1 {
background-image: url("/Content/avatars/Head.jpg");
background-repeat: no-repeat;
width: 7%;
height: 65px;
border-style: none;
margin-left: 90%;
margin-top: -8%;
}
.img2 {
width: 7%;
height: 65px;
border-style: none;
margin-left: 80%;
}
h2 span {
color: white;
font: bold 24px/45px Helvetica, Sans-Serif;
letter-spacing: -1px;
background: rgb(0, 0, 0);
background: rgba(0, 0, 0, 0.7);
padding: 10px;
}
.demo-card-wide.mdl-card {
width: 512px;
}
.demo-card-wide > .mdl-card__title {
color: #fff;
height: 176px;
}
.demo-card-wide > .mdl-card__menu {
color: #fff;
}
.container {
margin: 30px auto;
width: 85%;
height: 100%;
}
.warningMessage {
font-weight: bold;
color: Red;
}
</style>
<script>
$(function () {
if ($('#myModal').length) {
$('#myModal').modal('show');
}
});
</script>
<nav class="navbar navbar-light teal lighten-4" style="height: 100px">
<div class="container">
<div class="collapse navbar-toggleable-xs" id="collapseEx2" style="margin-top:-2%">
<img src="~/Content/truelogo.png" style="margin-left:-10%" />
#Html.ActionLink("Добавить технологическую карту", "Create", null, new { #class = "btn btn-success" })
<img src="~/Content/avatars/Head.jpg" class="rounded-circle img-responsive img1">
#Html.ActionLink("Отмена", "Index", "HeadDepartment", null, new { #class = "btn btn-danger", #style = "margin-left:100%; margin-top:-11%" })
</div>
</div>
</nav>
<div class="page-content">
<div class="container">
#{int i = 1;}
<table>
#foreach (var item in Model)
{
if (i % 4 == 1)
{
<tr></tr>
}
<td>
<div class="card">
<img class="img-fluid" src="#item.Image" alt="Card image cap">
<div class="card-block">
<center>
<hr />
<h4 class="card-title">#item.NameProduct</h4>
<hr />
#item.Description
<hr />
#{ var materials = item.SelectedMaterials.ToList();}
#foreach (var material in materials)
{
#Html.DisplayFor(model => material.ReferenceMaterial.NameMaterial) <b> Штук: </b>
#Html.DisplayFor(model => material.CountMaterial)
<br />
}
<br />
<center>
#Html.ActionLink("Настроить материалы", "EditMaterial", new { id = item.IdTechnologicalCard }, new { #class = "btn btn-success" })
<br />
#Html.ActionLink("Настроить количество", "EditCountOfMaterial", new { id = item.IdTechnologicalCard }, new { #class = "btn btn-success" })
</center>
<hr />
#Html.ActionLink("Удалить", "Delete", new { id = item.IdTechnologicalCard }, new { #class = "btn btn-danger" })
</center>
</div>
</div>
</td>
i++;
}
</table>
</div>
#if (TempData["message"] != null)
{
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria- labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
121212 <!--add your message here-->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data- dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
}
</div>
But when I deleting redirects to Index view without modal

You can pass error messages using the model state dictionary as well. In that case, you should be returning the same view back to the user instead of a redirect, so that user can try the action again.
catch (Exception ex)
{
ModelState.AddModelError(string.Empty,"Error! Try again.");
return View();
}
Now make sure you have the Validation helper methods being used in the view to render the error messages from the model state dictionary.
#Html.ValidationSummary(false)
With this approach, only the id will be passed back to the view (basically read from the model state dictionary), not all other fields you had. If you want all fields, use the same view model (which your view is strongly typed to) as the method parameter.

Exception handling using the modal
As you made it clear that you want to show the error in a modal window here is what you can do.
You need to again assign this TempData data into another TempData with in your Index method. Since the TempData is only alive from one controller to another.
And add this code in your index view.
#if (TempData["message"] != null)
{
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
#TempData["message"] <!--add your message here-->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
}
Then add this script in your index.cshtml.
$(function(){
if($('#myModal').length){
$('#myModal').modal('show');
}
});

Related

Angular : how to display a modal-dialog (chart) in ng-template

My application uses Angular 8 with Bootstrap and chart.js. I trying to render a bootstrap popup in an Angular ng-template directive. The popup (graph) is shown as soon as the user clicks in the last column in a table row. But as you can see on the picture, there is a white background, half the size of the actual graph. How can I get rid of this backgound ?
html part
<tbody>
<tr *ngFor="let stock of stockList; index as i" (click)="displaySelected(stock);">
<td style="width: 30px" scope="row">{{ i + 1 }}</td>
<td style="width: 40px">{{ stock.id }}</td>
<td style="width: 70px">{{ stock.symbol }}</td>
<td style="width: 70px">{{ stock.isin }}</td>
<td style="width: 180px">{{ stock.name }}</td>
<td style="width: 40px">{{ stock.liquid }}</td>
<td [class]="getFlagClass(stock.countryCode)" style="width: 14px"></td>
<td style="width: 180px">{{ stock.exchangeName }}</td>
<td style="width: 180px">{{ stock.sector }}</td>
<td style="width: 50px">{{ stock.active }}</td>
<td style="width: 30px"><img src="assets/img/chart.png" height="30" width="30" (click)="displayChart(content, stock);"/></td>
</tr>
</tbody>
</table>
</div>
<ng-template #content let-modal>
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">[name]</h5>
<button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<canvas id="myChart" width="1000" height="500"></canvas>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-dark" (click)="modal.close('Save click')">any action</button>
</div>
</div>
</div>
</ng-template>
Component part
displayChart(content, stock: Istock) {
// Open popup window
this.modalService.open(content, {ariaLabelledBy: 'modal-basic-title'}).result.then((result) => {
this.closeResult = `Closed with: ${result}`;
}, (reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
const today = new Date();
const dd = today.getDate();
const mm = today.getMonth();
const yyyy = today.getFullYear();
const dateTo: Date = new Date(yyyy, mm, dd);
const dateFrom: Date = new Date(yyyy - 1, mm, dd);
// retrieve dates and Prices
this.labelsDate = new Array();
this.dataPrices = new Array();
this.http.post(this.apiUrl + '/instrument/getPrices', {id: stock.id, from: dateFrom, to: dateTo } ).subscribe( (result: IinstrumentPrice[]) => {
result.forEach(x => {
this.labelsDate.push(x.date);
this.dataPrices.push(x.close);
});
this.canvas = document.getElementById('myChart');
this.ctx = this.canvas.getContext('2d');
// display chart
const myChart = new Chart(this.ctx, {
type: 'line',
data: {
labels: this.labelsDate,
datasets: [{
label: 'Daily prices',
data: this.dataPrices,
fill: false,
borderWidth: 2,
borderColor: 'black'
}]
},
options: {
elements: { point: { radius: 0 } },
responsive: false,
display: true
}
});
});
}
css part
.row-input {
font-size: 15px;
padding-top: 2px;
padding-right: 1px;
padding-bottom: 1px;
padding-left: 2px;
}
input {
font-size: 15px;
}
.flag-us {
background-size:contain;
background-position:50%;
background-repeat:no-repeat;
position:relative;
display:inline-block;
width:1.33333333em;
line-height:1em;
background-image:url(../../assets/img/flags/united-states-of-america.png);
}
.modal-dialog{
position: relative;
display: table; /* This is important */
overflow-y: auto;
overflow-x: auto;
width: auto;
min-width: 300px;
}
The solution is to set a parameter {"size: 'xl'} in the open method.
displayChart(content, stock: Istock) {
// Open popup window
this.modalService.open(content, {size: 'xl'}).result.then((result) => {
and the html is also changed
<ng-template #content let-modal>
<div class="modal-header">
<div class="row">
<div class="col-sm-6">
<h4 class="modal-title">{{instrumentName}}</h4>
</div>
<div class="col-sm-8">
<div>last trading day : {{lastTradingDay}}</div>
</div>
</div>
<button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<canvas id="myChart" width="1000" height="500"></canvas>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" (click)="modal.close('Close click')">Close</button>
</div>
</ng-template>

User photo disappears when I change the password

I have a form where the user's photo appears. Every time I change the user password, the photo disappears from the form. I already tried to take the image of the form but it did not solve. The password change is done through onSubmit.
HTML:
<form (ngSubmit)="onSubmit($event)">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Configuração do Usuário: <b> {{userId?.name}} </b></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="example-container" style="width: 100%; margin: auto; margin-top: 2%">
<img class="img-modal" style="border-radius: 50%; width: 60px; height: 60px;" src={{userId?.photo}}>
<div class="example-container password-width">
<mat-form-field>
<input matInput placeholder="Alterar a Senha" [type]="hide ? 'text' : 'password'" [(ngModel)]="senha" name="senha">
<mat-icon matSuffix (click)="hide = !hide">{{hide ? 'visibility' : 'visibility_off'}}</mat-icon>
</mat-form-field>
</div>
<app-panel-config-user></app-panel-config-user>
</div>
</div>
<div class="modal-footerButtonConfig">
<button type="button" class="btn btn-danger btn-sm buttonConfig" *ngIf="userId?.status == 1">Desativar
Usuário</button>
<button type="button" class="btn btn-success btn-sm buttonConfig" *ngIf="userId?.status == 0">Ativar
Usuário</button>
<button type="button" class="btn btn-sm buttonConfig buttonColor" style="background-color: #6239BD; color: white" *ngIf="userId?.is_admin == 0">Tornar Administrador</button>
<button type="button" class="btn btn-sm buttonConfig buttonColor" style="background-color: #6239BD; color: white" *ngIf="userId?.is_admin == 1">Remover Administrador</button>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Fechar</button>
<button type="submit" class="btn btn-sm buttonColor" style="background-color: #6239BD; color: white">Salvar</button>
</div>
</form>
Code change password:
onSubmit(
userPass: UserPass,
messageSucess: string = 'Senha alterada com Sucesso!',
messageError: string = 'Falha ao alterar a senha.',
action: string = '') {
userPass.password = this.senha;
return this.userService.putPass(this.idUser, userPass).subscribe(response => {
if (!response) {
console.log(Error);
} else {
this.userId = response;
if (this.userId['success'] === true) {
this.senha = '';
this.snackBar.open(messageSucess, action, {
duration: 4000,
panelClass: ['success-class']
});
} else {
this.snackBar.open(messageError, action, {
duration: 4000,
panelClass: ['error-class']
});
}
}
});
}
Your problem is the line
this.userId = response;
You are setting the userId to the response ({success: true}) - but the response isn't a userId!
Remove this line, and it should work again.

Buttons in Bootstrap (3) are getting rendered without any default padding when using React

I'm currently learning React and I'm trying to render some buttons in my app. However, when they're rendered in the page they all show all grouped together and without the default margin.
Image of buttons rendered without default margin using React
I'm unable to reproduce this problem when I render a static HTML version:
Image of buttons rendered with default margin using HTML only
I'm not sure at all how to troubleshoot this and I would like to be able to use Bootstrap in React without having to add my own CSS.
In case it helps, the exact same thing happened some time ago when I tried to append the same buttons using jQuery before starting to learn React. I was unable to fix it back then as well.
React code:
import React, { Component } from 'react';
class Container extends Component {
render() {
return(
<div className="container">
<div className="panel panel-default question">
<Title/>
<Body/>
</div>
</div>
)
};
};
class Title extends Component {
render() {
return(
<div className="panel-heading">
<h3 className="panel-title">Panel Title</h3>
</div>
);
};
};
class Body extends Component {
render() {
return(
<div className="panel-body">
<p className="panel-question">Question Content</p>
<textarea className="form-control" rows="5" id="comment"></textarea>
<div >
<OptionList/>
</div>
</div>
);
};
};
class OptionList extends Component {
render() {
return(
<div className="button-container text-center">
<button type="button" className="btn btn-primary">Option 1</button>
<button type="button" className="btn btn-primary">Option 2</button>
<button type="button" className="btn btn-primary">Option 3</button>
<button type="button" className="btn btn-primary">Option 4</button>
<button type="button" className="btn btn-primary">Option 5</button>
</div>
);
};
};
export default Container;
HTML Only:
<div class="container">
<div class="panel panel-default question">
<div class="panel-heading">
<h3 class="panel-title">Panel Title</h3>
</div>
<div class="panel-body">
<p class="panel-question">Question Content</p>
<textarea class="form-control" rows="5"></textarea>
<div >
<div class="button-container text-center" id="button-container">
<button type="button" class="btn btn-primary">Option 1</button>
<button type="button" class="btn btn-primary">Option 2</button>
<button type="button" class="btn btn-primary">Option 3</button>
<button type="button" class="btn btn-primary">Option 4</button>
<button type="button" class="btn btn-primary">Option 5</button>
</div>
</div>
</div>
</div>
</div>
Does anyone know how to overcome this issue? Will this happen with other React elements as well? Thanks for the help and any feedback you may have!
Edit:
I'm not using any custom CSS but the app is using the default CSS from create-react-app:
App.css
.App {
text-align: center;
}
.App-logo {
animation: App-logo-spin infinite 20s linear;
height: 80px;
}
.App-header {
background-color: #222;
height: 150px;
padding: 20px;
color: white;
}
.App-title {
font-size: 1.5em;
}
.App-intro {
font-size: large;
}
#keyframes App-logo-spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
index.css
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}

MVC logout Button Confirm Modal Popup Not working

Im develop the MVC project, Im developed the User Login session, Im add the user logout button for bootstrap modal popup confirmation box, but box is not working,How can i fix it.
Thank you
<header>
<a id="header-logo" href="#"></a>
<a class="navbar-brand" href="#"><img src="~/img/ekinitting _logo.png" class="img-responsive" style=" position: absolute; display: block; width: 260px; height: 65px; left: 10px; top: 10px;"></a>
#using (Html.BeginForm("LogOut", "Login", new { area = "" }, FormMethod.Post, new { id = "logoutForm" })){
#Html.AntiForgeryToken()
<a href="javascript:document.getElementById('logoutForm').submit()" style=" top:-28px;"><input type="image" id="myimage" src="~/img/log_out.png" style=" margin-top:15px; margin-left:150px; position:relative; float:right; " data-toggle="modal"
data-target="#basicModal" /></a>
}
<div class="col-lg-2" style="color:#ff0000; margin-top:28px; left:1055px; position:relative; ">
#Html.ActionLink("Hello " + ((eKnittingData.UserRegistration)Session["User"]).UserName + " :)", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Welcome", style = "color:#fada5b; text-decoration: none; font-size:14px;" })
</div>
<!--/.nav-collapse -->
<a href="~/Home/Index">
<input type="image" id="myimage" src="~/img/Red-home-icon.png" style="top:15px; position:relative; left:150px; float:right; " />
</a>
</header>
Modal
<div class="modal fade" id="basicModal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content" style="background-color:#ffffff; border:solid 4px #e85656;margin-top:253px; left:-25px;">
<div class="modal-header" style="background-color:#e85656; height:15px;">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true" style="margin-top:-12px;">x</button>
<span class="glyphicon glyphicon-warning-sign" style=" color:yellow; font-size:large; top:-10px; left:115px;" aria-hidden="true"></span>
<h4 class="modal-title" id="myModalLabel" style="text-align:center;"></h4>
</div>
<p style="text-align:center; font-family:'Ebrima'; color:black; margin-top:15px;"> <strong> Are you sure you want to logout? </strong></p>
<div class="modal-footer" style="text-align:center;">
<button type="button" class="btn btn-success btn-xs" style=" width:50px;">Yes</button>
<button type="button" class="btn btn-danger btn-xs" data-dismiss="modal" style=" width:50px;">No</button>
</div>
</div>
</div>
</div>
You should place your form inside the modal not to the logout button which is opening the modal.
Just put the form in the modal-body where the confirmation text is written in your code.
All you need to put the form outside to the modal-body and footer div.

ASP.Net Razor MVC Bootstrap Login Modal Validation

Using Bootstrap in my Razor page, I am opening a modal window:
<div class="container-fluid">
<div class="navbar navbar-fixed-top navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="offcanvas" data-target=".navbar-offcanvas" data-canvas="body">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand pull-right" href="#">
<img src="assets/img/logo-header.png" alt="Alternate Text for Image">
</a>
</div>
<div class="navbar-offcanvas offcanvas navmenu-fixed-left">
<a class="navmenu-brand" href="#">eServices</a>
<ul class="nav nav-justified">
<li>New Here?</li>
<li>Services</li>
<li>Sign In</li>
</ul>
</div>
</div>
</div>
<div class="modal fade" id="modalLogin" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<p>
<h3 class="modal-title" id="myModalLabel">Login to MyApplication</h3>
</p>
</div>
#using (Html.BeginForm("index", "home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { role = "form", #class = "form-horizontal" }))
{
#Html.AntiForgeryToken()
<div class="form-group #Html.ValidationErrorFor(m => m.Username, "has-error has-feedback")">
<div class="col-sm-12">
#Html.FormTextBoxFor(p => p.Username, new { #class = "form-control" })
#if (!Html.IsValid(m => m.Username))
{
<span class="glyphicon glyphicon-remove form-control-feedback"></span>
}
#Html.ValidationMessageFor(m => m.Username, null, new { #class = "help-block" })
</div>
</div>
<div class="form-group #Html.ValidationErrorFor(m => m.Password, "has-error has-feedback")">
<div class="col-sm-12">
#Html.FormPasswordFor(p => p.Password, new { #class = "form-control" })
#if (!Html.IsValid(m => m.Password))
{
<span class="glyphicon glyphicon-remove form-control-feedback"></span>
}
#Html.ValidationMessageFor(m => m.Password, null, new { #class = "help-block" })
</div>
</div>
#Html.ValidationSummary(true, string.Empty, new { #class = "test" }, "span")
<div class=" pull-right">
<p>
<button type="submit" class="btn btn-default">#Forms.ButtonSignin</button>
</p>
<br />
<p>
#Html.ActionLink("Forgot your username?", "ForgotUsername")
</p>
<p>
#Html.ActionLink("Forgot your password?", "ForgotPassword")
</p>
</div>
}
</div>
</div>
</div>
The issue I have is that, for example, I entered an incorrect username/password combination, the form validates, but the modal window closes. Is there a way to re-open the modal window after the form has posted if the validation triggered an error?
You could add a property named IsModalShown i.e.
public class AModel
{
public bool IsModalShown { get; set; }
}
Render this as a hidden for in your view i.e.
#Html.HiddenFor(m => m.IsModalShown)
When the modal is opened set the hidden value to true, this will enable the modal state to be posted back to the controller action i.e.
$('#modalLogin').on('show.bs.modal', function (e) {
$('#IsModalShown').val(true);
})
Please note the above will depend on the version of bootstrap you are using but there are other docs on the official site
Then add the following to your view that automatically pops it up
$(function(){
#if(Model.IsModalShown)
{
$('#signin_modal').modal('show');
}
});
I had a similar problem, but didn't have a model in view. Posting my solution, in case it would help someone. I wanted to show an error message stored in TempData (in case of wrong login/password combination, on which Batuta was asking).
Controller:
public ActionResult SignIn(string login, string password)
{
if (Membership.ValidateUser(login, password))
{
// something
}
else
{
TempData["message-error"] = "Wrong combination";
}
return RedirectToAction("Index", "Home");
}
Showing the message in modal window:
#if (TempData["message-error"] != null)
{
#TempData["message-error"]
}
Opening modal in index:
#if (TempData["message-error"] != null)
{
<script type="text/javascript">
$('#myModal').modal('show');
</script>
}
Maybe not that clean, but works for me.

Resources