form onsubmit doesn't work - javascript

#model MVC_STORE.Models.Product
#{
Layout = null;
}
<!DOCTYPE html>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>AddProduct</title>
</head>
<body>
<div>
<form id="formAdd" onsubmit=" return SendData(); return false;">
<table>
<tr>
<td>Serial number:</td>
<td>#Html.TextBoxFor(m => m.SerialNo) #Html.ValidationMessageFor(m => m.SerialNo)</td>
</tr>
<tr>
<td>Product name:</td>
<td>#Html.TextBoxFor(m => m.Name) #Html.ValidationMessageFor(m => m.Name)</td>
</tr>
<tr>
<td>Product price:</td>
<td>#Html.TextBoxFor(m => m.Price) #Html.ValidationMessageFor(m => m.Price)</td>
</tr>
<tr>
<td>Product quatity:</td>
<td>#Html.TextBoxFor(m => m.Quatity) #Html.ValidationMessageFor(m => m.Quatity)</td>
</tr>
</table>
<input type="submit" id="toAdd" value="Add product" />
</form>
#Html.Partial("ProductsTable")
<script language="javascript">
function SendData() {
$("#status").text("Saving product, please wait..");
var formData = $("#formAdd").serialize();
$.post("addProduct", formData, BindData);
$("#status").text("");
}
</script>
</div>
</body>
</html>
the onsubmit doesn't work for some reason, and I've read a lot of posts about it, but none of them helped me in this case.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace HW_MVC_STORE.Models
{
public class Product
{
[Key]
[RegularExpression("^[a-zA-Z0-9]+$", ErrorMessage = "Only upper- and lower- case letters and numbers.")]
[Required]
[StringLength(5,MinimumLength=5, ErrorMessage = "Please enter 5 characters serial.")]
public string SerialNo { get; set; }
[RegularExpression("^[a-zA-Z]+$", ErrorMessage = "Only upper- and lower- case letters")]
[Required]
[StringLength(10, MinimumLength=2, ErrorMessage="Please enter between 2 and 10 characters.")]
public string Name { get; set; }
[RegularExpression("^[0-9]+$", ErrorMessage = "Integers only")]
[Required]
public string Quatity { get; set; }
[RegularExpression("^([0-9]+[.][0-9]+)|([1-9]+[0-9]*)$", ErrorMessage = "Numbers only, bigger then zero")]
[Required]
public string Price { get; set; }
}
}
I've tried some suggestions from posts, but none of them worked.
<form id="formAdd" onsubmit="return SendData(); return false;">
<form id="formAdd" onsubmit="return SendData();">
<form id="formAdd" onsubmit="SendData()">
I don't understand why it's even calls the SendData() function, it doesn't suppose to leave the form until all the text-boxes are correctly filed.
how can I fix it or at least what is wrong with it?

You need:
<form id="formAdd" onsubmit="SendData(); return false;">
the function SendData doesn't return a value, thus return SendData(); doesn't make sense.
not returning false would cause a reload of the page (default action)
If the ajax POST in SendData is not working, we need more details on that.

Related

How do i can modify List Property in ASP.NET Razor Pages?

I am trying to delete a row from the table. I get the data when the page is loaded and it must be possible to delete one or more of these data. I managed to delete the row from the UI with javascript, however when I submit the form the propty doesn't get it with what data is left
So I don't know how to tell the backend what data I deleted.
I tried to do everything in Javascript, but i can't Modify the modelstate there.
thank you for your help
#for (int i=0;i < Model.AuftragsNummern.Count ;i++){
#Html.Hidden("Model.AuftragsNummern.index", i)
#Html.HiddenFor(x => x.AuftragsNummern[i])
<input type="hidden" name="Model.AuftragsNummern.index" value="#Model.AuftragsNummern" />
<tr>
<td>#Html.DisplayFor(x => Model.AuftragsNummern[i])</td>
<td><button asp-page-handler="AuftragDelete" onclick="deleteAuftrage(this)" class="btn btn-danger btn-rounded btn-sm my-0">delete</button></td>
#{}
</tr>
[BindProperty]
public List<int> AuftragsNummern { get; set; }
function deleteAuftrage(btn){
var row = btn.parentNode.parentNode
row.parentNode.removeChild(row)
}
Model Binding binds the property by name attribute which is in the frontend.
Only input/select/textarea type element with value can be bind to the backend when form submit, but your js just delete the row of #Html.DisplayFor(x => Model.AuftragsNummern[i]), multiple input elements still exists.
Here is a whole working demo you could follow:
Page
#page
#model IndexModel
<form method="post">
<table>
#for (int i = 0; i < Model.AuftragsNummern.Count; i++)
{
<tr>
<td>#Html.DisplayFor(x => Model.AuftragsNummern[i])</td>
<td><button onclick="deleteAuftrage(this)" class="btn btn-danger btn-rounded btn-sm my-0">delete</button></td>
<input type="hidden" name="AuftragsNummern" value="#Model.AuftragsNummern[i]" />
</tr>
}
</table>
<input type="submit" value="POST" />
</form>
#section Scripts
{
<script>
function deleteAuftrage(btn) {
var row = btn.parentNode.parentNode
row.parentNode.removeChild(row)
}
</script>
}
PageModel
public class IndexModel : PageModel
{
[BindProperty]
public List<int> AuftragsNummern { get; set; }
public void OnGet()
{
AuftragsNummern = new List<int>() { 1, 5, 6, 9, 7 };
}
public void OnPost()
{
}
}
Result

How to create a button for showing/hiding password in a MVC strongly typed razor view?

Scenario:
Creation of a basic HTML form with email, password fields and a submit button using ASP.NET MVC.
Required Cases: (1) Strongly bounded View - fetching variables from the controller and being defined explicitly as properties in a
Model. (2) Use HTML helpers instead of html tags for the input fields (3)
Provide an option to show/hide the characters while entering the password in the HTML
form on a web browser
The Model - LoginViewModel.cs
public class LoginViewModel
{
[DisplayName("Email")]
public string Email{ get; set; }
[DisplayName("Password")]
public string LoginPassword { get; set; }
}
The Controller - LoginController.cs
public class LoginController : Controller
{
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LoginViewModel log)
{
var Email = log.Email.ToLower();
var loginPassword = log.LoginPassword;
try
{
//code logic
return View("anotherView");
}
catch (System.Exception)
{
return View("exceptionView");
}
return View("tryAgainView");
}
The View - Index.cshtml
#model Project.Models.LoginViewModel
#{
ViewBag.Title = "Login";
Layout = "~/Views/Shared/_Layout.cshtml";//This view contains custom coding
}
<!--HTML-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/Scripts/js")
</head>
<body>
<header>
<div class="container">
<div class="row justify-content-center">
#using (Html.BeginForm("Login", "Login", FormMethod.Post))
{
<div class="content">
<!-- Email input -->
<div class="form-outline">
#Html.TextBoxFor(lvm => lvm.Email, new { #class = "form-control", required = "yes", #type = "email", #autocomplete = "off", #onsubmit = "return process()" })
#Html.LabelFor(lvm => lvm.Email, new { #class = "form-label" })
</div>
<!-- Password input -->
<div class="form-outline">
#Html.PasswordFor(lvm => lvm.LoginPassword, new { #class = "form-control", required = "yes", #autocomplete = "off", #onsubmit = "return process()" })
#Html.LabelFor(lvm => lvm.LoginPassword, new { #class = "form-label" })
</div>
<!-- Insert Submit button logic here -->
</div>
}
</div>
</div>
</div>
</header>
</body>
</html>
Checking the output HTML formatting (via the 'Inspect Element') of the password field
<input autocomplete="off" class="form-control" id="LoginViewModel_LoginPassword" name="LoginViewModel.LoginPassword" onsubmit="return process()" required="yes" type="password">
The Problem:
How do I add the password show/hide logic here? I have tried most of the javascript additions within the View by playing around
with the 'id' property in the HTML output formatting, but in
vain. I request you to please give a working solution which fits
into the implementation that I've presented here.
You'd need something along these lines (assuming you're using jQuery):
<form>
<input id ="pw_input" type="password" />
<button id="toggle">Toggle</button>
</form>
$('#toggle').click(function() {
if ($('#pw_input').attr('type') === "password") {
$('#pw_input').attr('type','text');
}
else {
$('#pw_input').attr('type','password');
}
})

How can i set skip parameter on button click in Query?

I have a set of records in which i am applying skip and take parameters in Entity Framework .
So in query I set take parameters constant which is 10.
I want to change skip parameter dynamically on each button click.
this is my code.
public ActionResult DateRecords()
{
if (!General.ValidateSession())
{
return RedirectToAction("Login", "User");
}
if (TempData["FromDate"] == null || TempData["toDate"] == null)
{
return View("InvalidDatesInput");
}
return View(this.GetRecordsByDate(0));
}
[HttpPost]
public ActionResult DateRecords(int skipParam)
{
if (!General.ValidateSession())
{
return RedirectToAction("Login", "User");
}
return View(this.GetRecordsByDate(skipParam));
}
public PassengerPaging GetRecordsByDate(int skipParam)
{
string fDate = TempData["FromDate"].ToString();
string tDate = TempData["toDate"].ToString();
TempData.Keep();
PassengerPaging psngr = new PassengerPaging();
psngr.Passengers = repository.GetRecords(fDate, tDate, skipParam).Select(x => new ViewModel.Passenger
{
ID = x.ID,
Name = x.Name,
FlightNo = FlightRepos.SelectByID(x.FlightId).FlightNo,
Airline = airlineRepo.SelectByID(x.FlightId).Name,
SeatNo = x.SeatNo,
SequenceNo = x.SequenceNo,
Date = x.Date,
EnterBy = x.EnterBy,
CheckinTime = x.CheckinTime,
CheckoutTime = x.CheckoutTime,
IsCheckout = x.IsCheckout
}).ToList();
psngr.Count = repository.GetRecordss(fDate, tDate).Count();
psngr.skip = skipParam;
return psngr;
}
This is my Model.
public class PassengerPaging
{
[Key]
//public int ID { get; set; }
//public List<Passenger> Passengers { get; set; }
//public int CurrentPageIndex { get; set; }
//public int Count { get; set; }
public int ID { get; set; }
public List<Passenger> Passengers { get; set; }
public int skip { get; set; }
public int Count { get; set; }
}
This is my View
<div>
#using (Html.BeginForm("DateRecords", "PassengerInfo", FormMethod.Post))
{
<h2>All Records</h2>
<div class="inner_page_about">
</div>
<br />
<br />
<div class="w3-row w3-border" style="width:100%">
<div class="w3-container w3-half, col-md-4" >
<input type="button" class="btn btn-outline-success" onclick="location.href='#Url.Action("ExportToExcel", "PassengerInfo")'" value="Export Detail Data" />
</div>
<div class="w3-container w3-half, col-md-4">
<input type="button" class="btn btn-outline-success" onclick="showGraph(false)" value="Month wise Graph" />
</div>
<div class="w3-container w3-half, col-md-4">
<input type="button" class="btn btn-outline-success" onclick="showGraph(true)" value="Date wise Graph" />
</div>
</div>
<br />
<hr />
<table id="1">
<thead>
<tr>
<th>Name</th>
<th>Seat Number</th>
<th>Sequence Number</th>
<th>Airline</th>
<th>FLight Number</th>
<th>Date</th>
<th>CheckIn Time</th>
<th>Checkout Time</th>
<th>IsCheckout</th>
<th>Enter By</th>
</tr>
</thead>
#foreach (var item in Model.Passengers)
{
<tr>
<td>#item.Name</td>
<td>#item.SeatNo</td>
<td>#item.SequenceNo</td>
<td>#item.Airline</td>
<td>#item.FlightNo</td>
<td>#item.Date</td>
<td>#item.CheckinTime</td>
<td>#item.CheckoutTime</td>
<td>#item.IsCheckout</td>
<td>#item.EnterBy</td>
</tr>
}
</table>
<br />
<input type="button" id="1" value="next" onclick="PagerClick(#Model.skip)">
<input type="hidden" id="hfCurrentPageIndex" name="skip" />
#* <input type="Submit" class="btn btn-outline-success" value="FeedBack">
<a onclick="location.href='#Url.Action("CheckOutUpdate", "PassengerInfo", new { id = item.ID })'"> <input type="Submit" class="btn btn-outline-success" value="CheckOut"></a>
<input type="Submit" class="btn btn-outline-success" value="Update">*#
#*<td>
<input type="Submit" class="btn btn-outline-success" value="FeedBack">
<a onclick="location.href='#Url.Action("CheckOutUpdate", "PassengerInfo", new { id = item.ID })'"> <input type="Submit" class="btn btn-outline-success" value="CheckOut"></a>
<input type="Submit" class="btn btn-outline-success" value="Update">
</td>*#
<canvas id="graph" width="30" height="40" style="display:none"></canvas>
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.js"></script>
<script type="text/javascript">
debugger;
function PagerClick(index) {
document.getElementById("hfCurrentPageIndex").value = index;
document.forms[0].submit();
}
Extra Information : This code is working fine but the prob is that if i have 100 records in my database it is showing 10 buttons as i put that type of logic , But i want only two buttons
Next
Previous
And on every click i want to add +10 on skip parameter initially it is 0
and on every click on Previous Button i want to -10 from skip parameter.

Read the file name using tag <input type = "file" > while uploading and rename it mvc + angularjs

I want to read the file name while uploading and rename it,save it to a path. For uploading the file I am using an upload image placed in a table. I am using -
#using (Html.BeginForm("file", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
to read the file name and the row values. But the issue is it reads the value of only first row whereever I click. Here is my code -
HTML -
<div>
#using (Html.BeginForm("file", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr ng-repeat = "{{data in list}}">
<td>{{data.Name}}</td>
<td>{{data.Id}}</td>
<td>
<label for="file">
<i class="fa fa-upload" id="hello" aria-hidden="true" >
</i>
</label>
<input type="file" name="file" id="file" onchange="this.form.submit();" />
<input type="text" name="Name" id="Name" />
<input type="text" name="Id" id="Id" />
</td>
</tr>
</table>
}
</div>
Controller -
public ActionResult file(HttpPostedFileBase file, string Name, string Id)
{
if (file != null && file.ContentLength > 0)
{
string fileName = file.FileName;
string newName = Name;
string fileId = Id;
}
else
{
ViewBag.Message = "You have not specified a file.";
}
return View("UploadPage");
}
Atpresent this is working but when I click on any upload image button, it only takes the first row Name and Id. I am not able to fix it. Please help.
Thanks
you are getting first row because when this.form.submit(); event triggers it will submit the form with all the rows in it and in action its just HttpPostedFileBase not List<HttpPostedFileBase> so it will get the data of first row because it will match the parameter. so one solution is you do
public ActionResult file(List<HttpPostedFileBase> file, List<string> Name, List<string> Id)
{
for (int i = 0; i < file.Count; i++)
{
var name = Name[i];
}
}
and a better way is to use a class
public class UploadFiles
{
public HttpPostedFileBase File { get; set; }
public string Name { get; set; }
public int Id { get; set; }
}
and your view will be
<div>
#using (Html.BeginForm("file", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr ng-repeat = "{{data in list}}">
<td>{{data.Name}}</td>
<td>{{data.Id}}</td>
<td>
<label for="file">
<i class="fa fa-upload" id="hello" aria-hidden="true" >
</i>
</label>
<input type="file" name="files[{{$index}}].File" id="file" />
<input type="text" name="files[{{$index}}].Name" id="Name" />
<input type="text" name="files[{{$index}}].Id" id="Id" />
</td>
</tr>
</table>
<button type="submit" >Upload All</button>
}
</div>
and in your action
public ActionResult AddAuto(List<UploadFiles> files)
{
foreach (var file in files)
{
// here you can access properties e.g file.File
}
}

Don't refresh page after uploading a file using a spring form.

I'm using a spring form to upload a document. The html form...
<form method="post" action="/SafeSiteLive/formTask3.do" enctype="multipart/form-data">
<table id="documentDetailsTable">
<tr>
<td>Document Type: </td>
<td><select id="documentType" name="type"> </select></td>
</tr>
<tr>
<td>
Document Name:
</td>
<td>
<input type="text" id="documentName" name="name"/>
</td>
</tr>
<tr id="newFile">
<td>
Choose a file:
</td>
<td>
<input type="file" name="file" />
</td>
</table>
<input type="text" style="display: none;" name="taskInstanceId" id="taskInstanceId">
<input id="uploadButton" value="Upload" type="submit"/>
<input class="closeButton" id="closeNew" value="Close" type="button"/>
</form>
This connects to my controller...
#RequestMapping(value = "/formTask3.do", method = RequestMethod.POST)
public ModelAndView handleFormTaskUpload3(#RequestParam("name") String name,
#RequestParam("type") String type,
#RequestParam("file") MultipartFile file,
#RequestParam("taskInstanceId") int taskInstanceId) {
System.out.println("handleFormUploadTask.1 ");
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
Document document = new Document();
document.setBytes(bytes);
String extension = "";
int i = file.getOriginalFilename().lastIndexOf('.');
if (i > 0) {
extension = file.getOriginalFilename().substring(i + 1);
}
document.setExtension(extension);
document.setName(name);
document.setType(DocType.documentType.valueOf(type));
Site site = SiteService.getSite(1);
document.setSite(site);
DocumentService.addDocument(document);
DocumentTaskLink docTaskLink = new DocumentTaskLink();
DocumentTaskKey docTaskKey = new DocumentTaskKey();
TaskInstance taskInstance = TaskInstanceService.getTaskInstance(taskInstanceId);
docTaskKey.setDocument(document);
docTaskKey.setTaskInstance(taskInstance);
docTaskLink.setKey(docTaskKey);
DocumentService.saveNewDocumentTaskLink(docTaskLink);
if (bytes != null) {
System.out.println("handleFormUpload. File uploaded with bytes size = " + bytes.length);
}
} catch (Exception e) {
e.printStackTrace();
}
return new ModelAndView("I dont want a new Model And View");
}
return new ModelAndView("redirect:uploadFailure");
}
The problem is this form returns a modelAndView which redirects the page.
I would like this to ultimately return a string saying 'success' or 'failure' in which I can respond by informing the user of this success with a dialog (without refreshing the page). I don't mind even just having this controller a void, mostly I just don't want to have to reload the page whenever a file is uploaded.
Is this possible?
How come when I make my controller a void the page still redirects to "/SafeSiteLive/formTask3.do"?
Can I return other things using this form upload controller?

Categories