Saving data through AngularJS - asp.net-mvc

Update:
I have replaced <input type=submit to <button ... and also remove the form tag from my html, after modifying my code i do not see it executing my JS and I have a debugger line in the code and it does not break....
I'm trying to POST data and I have all the code in placed and wired-up correctly (I believe) but when I try to Submit my page # My page gets refreshed, I don't see any event is firing and I have set debugger in the JS, and I do not see any JS error in developer tool
What I'm missing here apart from my code?
here is my code:
//HML code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My AngularJS App</title>
<script src="../AppScripts/RequesterAdd.js"></script>
</head>
<body>
<form>
<div ng-app="requesterAddModule" ng-controller="requesterAddController" class="container">
<h2> add requester</h2>
<div ng-show="ShowMessage">Record saved Successfully</div>
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>HostModel</h4>
<hr />
<div class="form-group">
<div>First Name:</div>
<div class="col-md-10">
<input type="text" ng-model="FirstName" required class="form-control input-lg" placeholder="First Name" />
</div>
</div>
<div class="form-group">
<div>Middle Name:</div>
<div class="col-md-10">
<input type="text" ng-model="MiddleName" required class="form-control input-lg" placeholder="Middle Name" />
</div>
</div>
<div class="form-group">
<div>Last Name:</div>
<div class="col-md-10">
<input type="text" ng-model="LastName" required class="form-control input-lg" placeholder="Last Name" />
</div>
</div>
<div class="form-group">
<div>eMail Address:</div>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<input type="text" ng-model="Email" required class="form-control input-lg" placeholder="Email Address" />
</div>
</div>
<div class="form-group">
<div>Is Host Active:</div>
<div class="col-md-10">
<input type="checkbox" ng-model="Active" required class="control-label col-md-2" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" id="btnCreate" data-ng-click="addRequester_ClickEvent" value="Create" class="btn btn-primary" />
</div>
</div>
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</div>
</form>
</body>
</html>
//JS:
var requesterAddModule = angular.module("requesterAddModule", []);
requesterAddModule.factory('requesterAddService',
['$http', function ($http) {
return {
addRequester: function (reqesterData) {
console.log(reqesterData);
debugger;
$http({
url: 'PersistRequester',
method: 'POST',
data: reqesterData
}).then (function (response) {
if (response !== 'undefined' && typeof(response) == 'object') {
window.location.href = '/'
}
},
function(response) {
//failed
}
);
}
};
}]);
requesterAddModule.controller('requesterAddController', ['$scope', '$http', '$window', 'requesterAddService', function ($scope, $http, $window, requesterAddService) {
$scope.addRequester_ClickEvent = function () {
var req = {};
debugger;
req["FirstName"] = $scope.FirstName;
req["MiddleName"] = $scope.MiddleName;
req["LastName"] = $scope.LastName;
req["Email"] = $scope.Email;
req["Active"] = $scope.Active;
requesterAddService.addRequester(req);
}
}]);
//MVC Server side code:
[HttpPost]
public JsonResult PersistRequester(Requester requester)
{
var req = requester;
//if (ModelState.IsValid)
// {
req.CreatedDateTime = DateTime.Now;
db.Requesters.Add(requester);
db.SaveChanges();
return Json(new { Status = "Success" });
//}
}

You're using a form without a method and action which will by default post to the current url. I would highly recommend not to use a form or at least not using an <input type="submit" /> which will default in all the browsers to submit the form.
You're clearly using Bootstrap 3 here so why not just remove the form tag and the submit button and replace it with another element which will not trigger the form post and style it with class="btn btn-primary". Some could argue against this practise along the graceful degradation guidelines but since this particular form is not built from ground up to support the non-js scenario, it is best not to allow browser submit at all.
Also, in your service where you're doing the actual post, you specifically tell the page to reload.
if (response !== 'undefined' && typeof(response) == 'object') {
window.location.href = '/'
}
You should pass this data back to the viewmodel so that the view can re-render and display the response.
If you change the url, the view state is lost and the page will simply render again to the initial state.

instead line
<input type="submit" id="btnCreate" data-ng-click="addRequester_ClickEvent" value="Create" class="btn btn-primary" />
please do
<button id="btnCreate" data-ng-click="addRequester_ClickEvent()" class="btn btn-primary" >Create</button>

I've just tested and is working for me replace:
<input type="submit" id="btnCreate" data-ng-click="addRequester_ClickEvent" value="Create" class="btn btn-primary" />
with
<button id="btnCreate" data-ng-click="addRequester_ClickEvent()" value="Create" class="btn btn-primary" >submit</button>
and I've change a bit your service to :
requesterAddModule.factory('requesterAddService',
['$http', function ($http)
{
return {
addRequester: function (reqesterData)
{
console.log(reqesterData);
debugger;
$http.post('PersistRequester', reqesterData).then(function (response)
{
if (response !== 'undefined' && typeof (response) == 'object') {
window.location.href = '/'
}
},
function (response)
{
//failed
}
);
}
};
}]);
it's posting to /home/PersistRequester if method 'PersistRequester' exist in other controller ie : foo controller change
$http.post('PersistRequester', reqesterData).then(function (response)
to $http.post('foo/PersistRequester', reqesterData).then(function (response)

Related

Viewbag content does not appear

I have an APS.Net web app Razor view where I attempt to display the Viewbag.errormessage.
The action method populates the viewbag but the view does not show the error message that is in the viewbag. It does not appear. Why?
The paragraph to which the Viewbag is attached to does not even appear per the 2nd pic. In the 1st pic, I can see that is there.
I also tried using 'TempData' but it produces the same result - not appearing.
Here is the action method (simplified):
[HttpPost]
public async Task<ActionResult> DeleteUserAccount(string userName, string
password)
{
try
{
if (string.IsNullOrEmpty(userName) ||
string.IsNullOrEmpty(password))
{
ViewBag.errormessage = "The 'user name' or 'password' is
invalid - empty. Please try again.";
}
else
{
// Cast.
if ((string)Session["UserName"] == userName)
{
}
else
{
ViewBag.errormessage = "Your 'user name' is invalid. It
is not the same as the 'user name' used at original sign
in. Please try again.";
}
}
}
catch (Exception ex1)
{
}
return View();
}
Here is the view:
#Html.AntiForgeryToken()
<div class="login-panel">
#if (ViewBag.errormessage != null)
{
<p class="alert alert-danger" id="errorMessage">#ViewBag.errormessage</p>
}
<div class="form-group">
<div class="col-md-12 col-xs-12">
<h2>Delete Account</h2>
<br />
<h4 class="verify"><strong>I will need to verify your identity in order to delete your account.</strong></h4>
<br />
<h4 class="verify"><strong>Please provide the following:</strong></h4>
</div>
</div>
<br />
<div class="form-group">
<div class="col-md-12 col-xs-12">
<br />
<label class="manadatory" for="UserName">User Name</label>
<input id="UserName" type="text" value="" name="UserName">
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-xs-12">
<br />
<label class="manadatory" for="Password">Password</label>
<input id="Password" type="text" value="" name="Password">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-0 col-md-10">
<br />
<input class="btn btn-primary deleteUserAccount" value="Delete Account">
#Html.ActionLink("Cancel", "Index", "User", null, new { #class = "btn btn-info" })
</div>
</div>
</div>
<div class="modal fade" id="myModal4" role="dialog" display="none">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body" style="padding:10px;">
<h4 class="text-center">Are you sure you want to permanently delete your account and all it contains? Continue ?</h4>
<div class="text-center">
<a class="btn btn-info btn-yes4">Yes</a>
<a class="btn btn-default btn-no4">No</a>
</div>
</div>
</div>
</div>
</div>
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#Styles.Render("~/Content/css")
<script type="text/javascript">
$(document).ready(function () {
$(".deleteUserAccount").click(function (e) {
var holdUserName = $('#UserName').val();
var holdPassword = $('#Password').val();
$("#myModal4").modal({
backdrop: 'static',
keyboard: false
});
$(".btn-yes4").click(function () {
$("#myModal4").modal("hide");
// Do the delete.
// - Pass the 2 fields.
$.ajax({
type: 'POST',
url: '#Url.Action("DeleteUserAccount", "User")',
data: { userName: holdUserName, password: holdPassword},
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
error: function (xhr, ajaxOptions, thrownError) {
alert('Critical Error: something is wrong in the call to DeleteUserAccount for delete! Status: ' + xhr.status + '. Error: ' + thrownError.toString() + '. Response Text: ' + xhr.responseText);
}
});
// Return.
return true;
});
$(".btn-no4").click(function () {
$("#myModal4").modal("hide");
return false;
});
$("#myModal4").on('hidden.bs.modal', function () {
$("#myModal4").remove();
});
});
})
</script>
https://dotnetfiddle.net/U6HGHD
Ajax makes a call and does not re-render a page
Controller
[HttpPost]
//I made method snchronous as it has no await, and there are no resources to add await to
public ActionResult DeleteUserAccount(string userName, string password)
{
var errorMessage = String.Empty;
try
{
if (string.IsNullOrEmpty(userName) ||
string.IsNullOrEmpty(password))
{
//since this method is ajax, the view will not re-render, so errors need
//to go into return value.
//ViewBag.errormessage = "The 'user name' or 'password' is invalid - empty.Please try again.";
errorMessage = "The 'user name' or 'password' is invalid - empty.Please try again.";
}
else
{
// Cast.
if ((string)Session["UserName"] == userName)
{
}
else
{
//ViewBag.errormessage = "Your 'user name' is invalid. It is not the same as the 'user name' used at original sign in. Please try again.";
errorMessage = "Your 'user name' is invalid. It is not the same as the 'user name' used at original sign in. Please try again.";
}
}
}
catch (Exception ex1){}
//return View();
//since this is ajax, I am returning a json
return Json(errorMessage, JsonRequestBehavior.AllowGet);
}
public ActionResult Index19()
{
return View();
}
View
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index19</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js" integrity="sha384-LtrjvnR4Twt/qOuYxE721u19sVFLVSA4hf/rRt6PrZTmiPltdZcI7q7PXQBYTKyf" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".deleteUserAccount").click(function (e) {
//put this in here
$("#myModal4").modal({
backdrop: 'static',
keyboard: false
});
//fixed the following line
});
$(".btn-yes4").click(function () {
//put these here
var holdUserName = $('#UserName').val();
var holdPassword = $('#Password').val();
$("#myModal4").modal("hide");
// Do the delete.
// - Pass the 2 fields.
$.ajax({
type: 'POST',
url: '#Url.Action("DeleteUserAccount", "Home")',
data: { userName: holdUserName, password: holdPassword },
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (data) {
if (data.length > 0) {
$("#errorMessage").css("display", "block");
}
else {
$("#errorMessage").css("display", "none");
}
$("#errorMessage").text(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Critical Error: something is wrong in the call to DeleteUserAccount for delete! Status: ' + xhr.status + '. Error: ' + thrownError.toString() + '. Response Text: ' + xhr.responseText);
}
});
// Return.
return true;
});
$(".btn-no4").click(function () {
$("#myModal4").modal("hide");
return false;
});
//$("#myModal4").on('hidden.bs.modal', function () {
// $("#myModal4").remove();
//});
});
</script>
</head>
<body>
#Html.AntiForgeryToken()
<div class="login-panel">
#*took out condition, and started with style none*#
#*#if (ViewBag.errormessage != null)
{*#
<p class="alert alert-danger" id="errorMessage" style="display:none">#ViewBag.errormessage</p>
#*}*#
<div class="form-group">
<div class="col-md-12 col-xs-12">
<h2>Delete Account</h2>
<br />
<h4 class="verify"><strong>I will need to verify your identity in order to delete your account.</strong></h4>
<br />
<h4 class="verify"><strong>Please provide the following:</strong></h4>
</div>
</div>
<br />
<div class="form-group">
<div class="col-md-12 col-xs-12">
<br />
<label class="manadatory" for="UserName">User Name</label>
<input id="UserName" type="text" value="" name="UserName">
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-xs-12">
<br />
<label class="manadatory" for="Password">Password</label>
<input id="Password" type="text" value="" name="Password">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-0 col-md-10">
<br />
<input class="btn btn-primary deleteUserAccount" value="Delete Account">
#Html.ActionLink("Cancel", "Index", "User", null, new { #class = "btn btn-info" })
</div>
</div>
</div>
<div class="modal fade" id="myModal4" role="dialog" display="none">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body" style="padding:10px;">
<h4 class="text-center">Are you sure you want to permanently delete your account and all it contains? Continue ?</h4>
<div class="text-center">
<a class="btn btn-info btn-yes4">Yes</a>
<a class="btn btn-default btn-no4">No</a>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

Get object from controller to view using ajax in .net mvc core

Controller:
[HttpGet]
public IActionResult Edit(int id)
{
Teacher teacher = teacherService.GetTeacherById(id);
EditTeacherData(teacher);
return View();
}
public JsonResult EditTeacherData( Teacher teacher)
{
return Json(teacher);
}
Ajax:
$.ajax({
type: "GET",
url: "/Teacher/EditTeacherData",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) {
debugger;
console.log(data)
},
error: function (response) {
debugger;
alert('eror');
}
});
View:
#model StudentTeacher.Models.TeacherViewModel
#{
ViewData["Title"] = "EditTeacher";
}
<h1>EditTeacher</h1>
<h4>Teacher</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form id="AddTeacherForm">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="TeacherId" id="TeacherId" />
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" id="Name" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Designation" class="control-label"></label>
<input asp-for="Designation" class="form-control" id="Designation" />
<span asp-validation-for="Designation" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Education" class="control-label"></label>
<input asp-for="Education" class="form-control" id="Education" />
<span asp-validation-for="Education" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="JoiningDate" class="control-label"></label>
<input asp-for="JoiningDate" class="form-control" id="JoiningDate"/>
<span asp-validation-for="JoiningDate" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" id="Submit" />
</div>
</form>
</div>
</div>
teacherService is a service that retrieves data that match with id. But it return null object. When I use this EditTeacherData(teacher); ajax not return a null object But in debugger model show value takes this function. I just wanna get an object through ajax and show data in the field via ajax.
Obviously, there is no parameter passed in to the controller in your ajax, so Edit method will never receive the parameter passed in.
You can implement it with EF core. If you want to use ajax, you can refer to this.
You can also achieve it without ajax, it much easier, please refer to this.
You are not sending data from your ajax request. Please read this for clear understanding
$('#Submit').click(function(){
var formData = $('#AddTeacherForm').serialize();
$.ajax({
type: "GET",
url: "/Teacher/EditTeacherData",
data: formData,
success: function (data) {
debugger;
console.log(data)
},
error: function (response) {
debugger;
alert('eror');
}
});
})

Show or Hide History in MVC

I am working on a registration form. I want to show and hide my users past registrations using a button.The button should only show or hide registrations that are gone not the upcoming ones This is what I have so far. Pleasssseeee Help.
<div class="Table01">
<button id="older">Show Registration History</button>
#foreach (var sm in Model)
{
var tmp = #sm.SeminarNm.Replace("&", "and");
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 well table-item" align="left" data-toggle="tooltip" data-eventtype="#tmp" data-placement="top" title="#tmp">
<span class="sortName mid-weight"> #sm.SeminarNm</span>
<span class="sortDate alert-info">(ON #string.Format("{0:yyyy-MM-dd}", #sm.SessionStartDT) IN #sm.SessionCityNm)</span>
<div class="row " style="margin-top:10px">
#if (#sm.IsEditable == "Y")
{
using (Html.BeginForm("EditRegister", "App", FormMethod.Post, new { onclick = "showPageLoadingSpinner()" }))
{ #Html.AntiForgeryToken()
<div class="col-xs-12 col-md-6 col-lg-6">
<input class="btn btn-success " name="submitButton" type="submit" value="Edit" />
<input type="hidden" value="#sm.RegistrantSeq" name="hiddenseq" />
<input type="hidden" value="0" name="cntView" />
<input type="hidden" value="EditRegister" name="cntStage" />
</div>
}
}
#using (Html.BeginForm("ViewRegister", "App", FormMethod.Post))
{ #Html.AntiForgeryToken()
<div class="col-xs-12 col-md-6 col-lg-6 col">
<input class="btn btn-info" name="submitButton" type="submit" value="View" />
<input type="hidden" value="#sm.RegistrantSeq" name="hiddenseq" />
<input type="hidden" value="ViewRegister" name="cntStage" />
</div>
}
//
</div>
}
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script>
var $btns = $('.btn').click(function () {
if (this.id == 'older') {
$('#child > div').toggle(450);
}
$btns.removeClass('active');
$(this).addClass('active');
})
</script>
My Program Pic
I dont know if I need some sorting javascript function to display only those sessions that are in the past. Nothing seems to be working.
Assuming old registrations are any item with SessionStartDT value earlier than current date, you can set an html data attribute on each item's container div indicating whether it is an old item or new item and when user clicks the hide/show button, toggle the visibility of these items.
#foreach (var sm in Model)
{
<div data-old="#(p.SessionStartDT.Date < DateTime.Today.Date)">
<!-- your existing code for rendering each item goes here -->
</div>
}
And in the javascript part, when the button is clicked, make select the elements who's data-old attribute value is True (which we set via our C# expression which results in a boolean value) and toggle the visibility.
$(document).ready(function() {
$("#older").click(function(e) {
e.preventDefault();
$("[data-old='True']").toggle();
});
});

How to add multiple fields in bootbox.prompt in mvc

I want to add a project name and task name while clicking on a particular date in fullcalendar but I don't know how to use bootbox.prompt or bootbox.dialog with more than one fields so can you help me out?
select: function (start, end, allDay) {
debugger;
bootbox.prompt("Add New Event", function (title) {
debugger;
if (title !== null) {
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay,
className: 'label-info'
},
true // make the event "stick"
);
}
});
It's quite simple, we can use bootbox dialog for that
bootbox.dialog({
title: 'Add New Event',
message: $('#form'),
show: false,
}).on("shown.bs.modal", function (e) {
$('#form').show()
}).on('hide.bs.modal', function (e) {
/**
* Bootbox will remove the modal (including the body which contains the login form)
* after hiding the modal
* Therefor, we need to backup the form
*/
$('#form').hide().appendTo('body');
})
.modal('show');
calendar.fullCalendar('unselect');
}
In html
<form id="form" method="post" class="form-horizontal" style="display: none;">
<div class="form-group">
<label class="col-xs-3 control-label">Username</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="username" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Password</label>
<div class="col-xs-5">
<input type="password" class="form-control" name="password" />
</div>
</div>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-3">
<button type="submit" class="btn btn-primary" style="float:right;">Login</button>
</div>
</div>

MVC/Razor File Upload View

I self admitted newbie, but I have a view with some code I pasted to provide a file upload. The function works but if the code is in, the "Save" button for the View that was already there stops working. If I had to guess it has something to do with the "HTML.BeginForm" line being there twice.
Here is the top of the view,
#model BrooksSOR.Models.dataOffender
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<div >
<h2>Upload Files in MVC</h2>
<img src="#Model.Photograph" width="250" height="250" />*
#using (Html.BeginForm("FileUpload", "SOR",
FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input name="uploadFile" type="file" />
<input type="submit" value="Upload File"/>
<input type="hidden" name="parmPersonID" value="#Model.PersonID" />
}
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>dataOffender</legend>
<p>
<input type="submit" value="Save" />
<input id="Details" type="button" value="Details" />
</p>
</fieldset>
Remove the #html.BeginForm
The script you would need to send for a file and some other fields with it.
//Purpose: Form Submit: SAVE Client
document.getElementById('frmPage').onsubmit = function (e) {
debugger;
var file = document.getElementById('fileToUpload').files[0];
var filename;
if (file) {
filename = file.name;
}
else {
filename = "";
}
$('#Image').val(filename);
var formObj = $(this);
var formURL = '#Url.Action("SaveMethod", "ControllerName")';
var formData = new FormData(this);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function (data, textStatus, jqXHR) {
debugger;
alert("Client saved successfully");
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
e.preventDefault(); //Prevent Default action.
}
This is the design:
<div>
<form id="frmPage" class="form-horizontal">
<div class="form-body">
<div class="form-group">
<label id="lblImage" class="col-md-3 control-label">Upload File</label>
<div class="col-md-4">
<input type="file" id="fileToUpload" name="file" />
</div>
</div>
<div class="modal-footer" style="margin-top: 0px">
<div class="pull-right">
<button type="submit" id="btnSave" class="btn blue Save">Save</button>
</div>
</div>
</form>
</div>
Here: The btnSave is submit type, so it will submit that particular form. and form named frmPage will do the jquery script we added.

Resources