MVC bootstrap popup opens multiple times - c#

When I click in a button to open my popup form, it seems that it is being opened multiple times and in the browser console I get the error "(3) Uncaught TypeError: Cannot read property 'find' of null". What am I missing?
View containing the button:
<script src="~/Scripts/myscripts/JobOffers/JobOfferPopup.js"></script>
<div id="createJobOfferModal"></div>
<div id="jobOfferButtonsBar">
<div style="float:left; padding: 0px 5px 5px 5px;">
<a class="btn btn-default" id="createJobOfferBtn" href="" data-url="#Url.Action("CreateOrUpdate", "JobOffers", new { jobOfferId = 0 })">Create</a>
</div>
</div>
Popup View Code:
<div class="modal fade bs-example-modal-lg jobOfferForm" tabindex="-1" role="dialog" aria-labelledby="createJobOffer" aria-hidden="true">
<div class="modal-dialog modal-lg" style="overflow-y:auto; max-height:70vh">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="createJobOfferLabel"> #Model.PopupTitle </h4>
</div>
<div class="modal-body" data-val="5">
<form class="form-horizontal" role="form">
<div class="form-group" style="display:none;">
<label class="col-sm-2 control-label">#Html.LabelFor(model => model.Id)</label>
<div class="col-sm-10">
#Html.HiddenFor(model => model.Id, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">#Html.LabelFor(model => model.Client) </label>
<div class="col-sm-10">
<input type="text" class="form-control" id="Client" value="#Model.Client" style="width:25%;">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="saveJobOfferBtn" data-url="#Url.Action("CreateOrUpdate", "JobOffers" )">Save changes</button>
</div>
</div>
</div>
</div>
Jquery Code:
$(document).ready(function () {
$('#createJobOfferBtn').click(function () {
$.ajax({
url: $(this).data("url"),
type: 'GET',
cache: false,
success: function (result) {
console.log("opened");
$("#createJobOfferModal").html(result).find('.modal').modal({
show: true
});
}
});
return false;
});
});

Related

I've created a modal component and that doesn't work

I'm new in coding with ASP.NET Core. I created a CRUD functions in my application and then i decided to change some rules like Create New do not navigate to another tab it will be navigated to a component modal. So I did the steps that it shown in a tutorial but I didn't get a result .
Here's the page :
This is the code in index.cshtml:
#model IEnumerable<PermissionManagement.MVC.Models.Segment>
#{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div id="PlaceHolderHere"></div>
<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#addSegment" asp-action="_SegmentModelPartial" data-url="#Url.Action("Create")"> Create </button>
And this is the code wrote it in SegmentModelPartial:
#model Segment
<div class="modal fade" id="addSegment">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addSegmentLabel">Modal title</h5>
<button type="button" class="btn-close" data-dismiss="modal" aria-label="Close">
<span>x</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="SName" class="control-label">Nom</label>
<input asp-for="SName" class="form-control" />
<span asp-validation-for="SName" class="text-danger"></span>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group ">
<label asp-for="SRang" class="control-label">Rang</label>
<input asp-for="SRang" class="form-control" />
<span asp-validation-for="SRang" class="text-danger"></span>
</div>
</div>
</form>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-save="modal">Save changes</button>
</div>
</div>
</div>
</div>
This is my code in site.js:
$(function () {
var PlaceHolderElement = $('#PlaceHolderHere');
$('button[data-toggle="ajax-modal"]').click(function (event) {
var url = $(this).data('url');
$.get(url).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
})
})
PlaceHolderElement.on('click', '[data-save="modal"]', function (event) {
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = form.serialize();
$.post(actionUrl, sendData).done(function (data)){
PlaceHolderElement.find('.modal').modal('hide');
})
})
})
And finally this is the controller:
[HttpGet]
public IActionResult Create()
{
Segment seg = new Segment();
return PartialView("_SegmentModelPartial", seg);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Segment segment)
{
_context.Add(segment);
await _context.SaveChangesAsync();
return PartialView("_SegmentModelPartial", segment);
}

Bootstrap - present confirmation modal after post back to controller

I am trying to create a Bootstrap modal pop up "Ticket successfully created" once you submit a form which posts data through to IActionResult to add to database. However my modal is like transparent with just text and I'm also getting a runtime error of : Obj ref not set to an instance of object
I have a feeling that modal popup is causing the passing of data back to the controller to not work. What is the way around this?
GetTicket view
#model Project.HelpDeskViewModel
<fieldset>
#using (Html.BeginForm())
{
<div class="container">
<div class="form-group">
<div class="row m-4 text-center">
<div class="col-4">
</div>
<div class="col-4">
<h2 style="text-align:center;font-weight:bold">Get A Ticket</h2>
</div>
</div>
</div>
<div class="form-group">
<div class="row m-3">
<div class="col-4" style="text-align:left">
#Html.LabelFor(m => m.category)
</div>
<div class="col-4">
#Html.DropDownListFor(m => m.category, new SelectList(Model.categoryList, "Value", "Text"), "Select category", new { #class = "form-control" })#Html.ValidationMessageFor(model => model.category,
"", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="row m-3">
<div class="col-4" style="text-align:left">
#Html.LabelFor(m => m.ticketDescription)
</div>
<div class="col-4">
#Html.TextAreaFor(m => m.ticketDescription, new { #class = "form-control" })#Html.ValidationMessageFor(model => model.ticketDescription,
"", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#*Modal for ticket creation*#
<div class="modal" id="MyModal" role="dialog">
<div class="modal-dialog">
<div class="model-content">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h4>Ticket Created</h4>
</div>
<div class="modal-body">
<p> Your Helpdesk ticket has been succesfully submitted</p>
</div>
<div class="modal-footer">
<button class="btn btn-primary" data-dismiss="modal"> close</button>
</div>
</div>
</div>
</div>
</div>
<div class="row m-3">
<div class="col-4">
</div>
<div class="col-4" style="text-align:left">
<button type="submit" class="btn btn-primary form-control" data-target="#MyModal" data-toggle="modal">Submit</button>
</div>
</div>
</div>
}
</fieldset>
Controller
[HttpPost]
public IActionResult GetTicket(HelpDeskViewModel h)
{
HelpDeskViewModel sess = new HelpDeskViewModel();
try
{
//session variable passing userID
sess.userID = HttpContext.Session.GetString("userID");
if (!ModelState.IsValid) return View(h);
//h.empID = null; //add ticket record without employeeID - ticket hasn't been assigned yet
h.userID = sess.userID; //add userID from session
_db.helpdesk.Add(h);
_db.SaveChanges();
}
catch (Exception ex)
{
global.gLogger.log.Debug("Debug message: ", ex.Message);
global.gLogger.log.Error(new Exception(), ex.Message);
global.gLogger.log.Error(new Exception(), ex.StackTrace);
global.gLogger.log.Fatal("Fatal message: ", ex.Message); ;
}
return View("GetTicket");
}
You can use ViewBag for open bootstrap modal after successfully return from server to client
Client Side View
#if(ViewBag.SuccessfullyTicketCreated != null)
{
<script>
$('#myModal').modal('show'); // open model by use jQuery
</script>
}
Server side Controller
_db.SaveChanges();
ViewBag.SuccessfullyTicketCreated = true; // create ViewBag after savechange success
I hope help you simple way
Only use of ajax call can solve your problem without creating any further issues. if you are not using jQuery, you can also send ajax call using Javascript using fetch() method.
<form id="form" action="/Controller/GetTicket" method="post">
<div class="container">
<div class="form-group">
<div class="row m-4 text-center">
<div class="col-4">
</div>
<div class="col-4">
<h2 style="text-align:center;font-weight:bold">Get A Ticket</h2>
</div>
</div>
</div>
<div class="form-group">
<div class="row m-3">
<div class="col-4" style="text-align:left">
#Html.LabelFor(m => m.category)
</div>
<div class="col-4">
#Html.DropDownListFor(m => m.category, new SelectList(Model.categoryList, "Value", "Text"), "Select category", new { #class = "form-control" })#Html.ValidationMessageFor(model => model.category,
"", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="row m-3">
<div class="col-4" style="text-align:left">
#Html.LabelFor(m => m.ticketDescription)
</div>
<div class="col-4">
#Html.TextAreaFor(m => m.ticketDescription, new { #class = "form-control" })#Html.ValidationMessageFor(model => model.ticketDescription,
"", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#*Modal for ticket creation*#
<div class="modal" id="MyModal" role="dialog">
<div class="modal-dialog">
<div class="model-content">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h4>Ticket Created</h4>
</div>
<div class="modal-body">
<p> Your Helpdesk ticket has been succesfully submitted</p>
</div>
<div class="modal-footer">
<button class="btn btn-primary" data-dismiss="modal"> close</button>
</div>
</div>
</div>
</div>
</div>
<div class="row m-3">
<div class="col-4">
</div>
<div class="col-4" style="text-align:left">
<button type="submit" class="btn btn-primary form-control" data-target="#MyModal" data-toggle="modal">Submit</button>
</div>
</div>
</div>
</form>
Use Javascript:
<script> function onSubmit(){
$.ajax({
url:'/Controller/GetTicket',
type:'post',
data: $('#form').serialize(),
success: function(){
// code here;}
})
}</script>

How to create new form when clicking button in asp.net mvc or jquery?

I have a card and what i want to do, is when a user click(create course) button it must generate new content(asp.net mvc) or dashboard that is empty. I have some ideas around this. Let me share below;
<div class="row">
<div class="col-xs-3 ml-auto">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Start New Course
</button>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Start New Course</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="form-group">
<label for="CourseName" class="col-sm-2 col-form-label">CourseName:</label>
<div class="col-sm-6">
#Html.EditorFor(model => model.CourseName, new { htmlAttributes = new { #class = "form-control", autofocus = "autofocus", placeholder = "CourseName" } })
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary">Create Course</button>
</div>
</div>
</div>
</div>
// Jquery
<a class="btn btn-large btn-success" id="fire" href="/Controller/Courses.chtml#">Create Courses</a>
$('#fire').on('click', function (e) {
// dont know what to put here....?
})
I dont know if my logic is wrong and need some ideas around. Meaning what i want when i click the create button from the modal form it must take me to the new content(asp.net mvc). Something along this line
Change the href value, replace the ActionResultName and ControllerName, see below:
<a class="btn btn-large btn-success" id="fire" href="#Url.Action("ActionResultName","ControllerName")">Create Courses</a>

On After Render a Modal razor component start a JavaScript

I have a blazor app with an razor component as modal open by
Open the modal.razor
<ModalScan #ref="ModalScan"><p>Scanner</p></ModalScan>
<button class="btn btn-primary" #onclick="ScanStart">Start Scann</button>
#code{
ModalScan ModalScan;
void ScanStart()
{
ModalScan.Show();
}
}
the modal.razor
#if (_Show)
{
<div class="modal fade show" style="display: block;">
<div class="modal-dialog" style="width: 90%;" #>
<div id="modal_fullscreen" class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Scanner</h5>
<button type="button" class="close" data-dismiss="modal" #onclick="Show">×</button>
</div>
<div class="modal-body">
<form>
<div class="container">
<div class="form-row">
<div id="loadingMessage">Unable to access video stream </div>
<canvas style="width: 100%;" id="canvas" hidden></canvas>
<div id="output" hidden>
<div id="outputMessage">No detected.</div>
<div hidden>
<input type="text" id="outputData" value="#CurrentValue"
#onchange="#((ChangeEventArgs __e) => CurrentValue = __e.Value.ToString())" />
</div>
</div>
</div>
<div class="form-row">
<button type="button" class="btn btn-dark" #onclick="ScanResume">Scan</button>
</div>
</div>
</form>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal" #onclick="Show">Abort</button>
<button type="button" class="btn btn-primary" #onclick="saveChanges">Ok</button>
</div>
</div>
</div>
</div>
</div>
<div class="modal-backdrop fade show"></div>
}
After this modal.razor is load, i will start a js-Script.
I can only start with a button, then the DOM is not loading when
i invoke the Javascript on the Show() void.
On a razor page works it with:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JSRuntime.InvokeVoidAsync("startScanner");
}
}
public async void Show()
{
_Show = !_Show;
if (_Show)
{
}
}
but not on the modal.
Is there any event to check if modal is load complete from razor componetes in my modal?

how to get value of the editable text in angular controller

my index page is here
<div ng-app="CommentApp" ng-controller="MyController">
<div class=" col-md-12">
<div class="alert alert-info"><h2 class="text-center">Comment App</h2></div>
<div id="CommentList" class="container col-md-7" scroll="Comments" style="height:650px; overflow:scroll">
<div class="row" style="border:0px solid;padding:20px;" ng-repeat="Comment in Comments | orderBy:'LastUpdateTime'">
<div class="well well-sm row">
<div class="col-md-8">
**<h3><text style="color:mediumpurple;" e-form="rowform" data-ng-model="UpdateCommentText" editable-text="Comment.CommentText">{{Comment.CommentText || 'Empty'}}</text></h3>**
</div>
<div class="col-md-4 pull-right" style="margin-top:17px">
<div class="buttons pull-right">
<form editable-form name="rowform" ng-show="rowform.$visible" class="form-buttons form-inline">
<button type="submit" ng-disabled="rowform.$waiting" ng-click="EditComment()" class="btn btn-primary">
Save
</button>
<button type="button" ng-disabled="rowform.$waiting" ng-click="rowform.$cancel()" class="btn btn-default">
Cancel
</button>
</form>
</div>
<div class="buttons pull-right" ng-show="!rowform.$visible">
<button class="btn btn-primary" ng-click="rowform.$show()">Edit</button>
<button class="btn btn-danger" ng-click="RemoveComment(Comment)">Delete</button>
</div>
</div>
</div>
<div class="col-md-12 row" style="margin-bottom:10px" ng-repeat="img in Comment.Images">
<img style="margin-bottom:15px" src="{{img}}" />
</div>
<h2 class="pull-right" style="color:green;font-size:15px; margin-right:20px">By User {{Comment.Id}}</h2>
<h2 class="pull-right" style="color: darkviolet; font-size: 15px; margin-right: 20px">{{Comment.LastUpdateTime.slice(6,-2) | date: 'hh:mm a dd-MMM-yyyy' }}</h2>
<div class="clearfix"> </div>
<hr />
</div>
</div>
</div>
<div class="col-sm-10" style="font-size:17px">
<form novalidate name="f1" ng-submit="AddComment()">
<div style="color: red">{{Message}}</div>
<div class="col-sm-1">
<div class="glyphicon glyphicon-plus" style="height: 50px;border:1px solid; width: 50px; cursor:pointer;" onclick="getFile()">
<div style="height: 0px;width:0px; overflow:hidden;">
<input id="filesel" type="file" name="file" accept="image/*" onchange="angular.element(this).scope().selectFileforUpload(this.files)" required multiple />
</div>
</div>
<span class="error">{{FileInvalidMessage}}</span>
</div>
<div class="col-sm-6 pull-left">
<input type="text" placeholder="Enter Your Comment Here" style="height: 50px;font-size:30px;width:500px" name=" ufiledescription" ng-model="CommentText" class="{{(IsFormSubmitted?'ng-dirty' + (f1.uFileDescription.$invalid?' ng-invalid':''):'')}}" autofocus />
</div>
<div class="col-sm-3 pull-left">
<input class="btn btn-primary" style="height:50px;width:100px" value="Send" id="Submit" type="submit" />
</div>
</form>
</div>
</div>
my angular controller
app.controller("MyController", function ($scope, MyServices,$http) {
// Get All Comments
GetAllComments();
function GetAllComments() {
var getData = MyServices.getComments();
getData.then(function (cmnt) {
$scope.Comments = cmnt.data;
},
function () {
alert('Error in getting Comments');
});
};
// Add New Comment
$scope.AddComment = function () {
var Comment = {
CommentText: $scope.CommentText
};
var getData = MyServices.AddCmnt(Comment);
getData.then(function (ResultMsg) {
GetAllComments();
alert(ResultMsg.data);
});
ClearFields();
$scope.refresh();
};
// Edit The Comment
$scope.EditComment = function () {
Comment =
{
Id: Comment.Id,
CommentText: $scope.UpdateCommentText
}
alert(Comment.CommentText);
//var getData = MyServices.getCommentById(Comment.Id);
var getData = MyServices.EditCmnt(Comment);
getData.then(function (ResultMsg) {
alert(ResultMsg.data);
GetAllComments();
});
};
// Delete The Comment
$scope.RemoveComment = function (Comment) {
var getData = MyServices.DeleteCmnt(Comment);
getData.then(function (ResultMsg) {
alert(ResultMsg.data);
GetAllComments();
},
function () {
alert('Error in Deleting Comment');
});
}
//Clear Fields After Comment Addition
function ClearFields() {
$scope.CommentText = "";
angular.forEach(angular.element("input[type='file']"), function (inputElem) {
angular.element(inputElem).val(null);
});
};
});
in the index page the comment.commenttext which is editable text and coming from database on click of edit there will be a editable text box and after editing the text on click of save button i cant get value of edited text what shpold to in editcomment section to retrieve value of edited text?
i tried $scope.Comment.commenttext but it is undefined..
help me thanks in advance..
You have a double bind here:
<h3>
<text
style="color:mediumpurple;"
e-form="rowform"
data-ng-model="UpdateCommentText"
editable-text="Comment.CommentText"
>
{{Comment.CommentText || 'Empty'}}
</text>
</h3>
So basically you see what is binded with data-ng-model, not experssion in {{ }} Try getting UpdateCommentText value. Maybe this helps.

Categories