how to send email using asp.net and html page - javascript

I have a contact.html page where i have textboxex page for username,email,phone,subject, message and a submit button.
<form class="contact-page-form-1">
<div class="row clearfix">
<div class="col-md-6 col-sm-6 col-xs-12 form-group">
<input type="text" name="username" placeholder="Your Name*" id="username" required>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group">
<input type="email" name="email" placeholder="Email Address*" id="email" required>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group">
<input type="text" name="phone" placeholder="Phone Num" id="phone" required>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group">
<input type="text" name="subject" placeholder="Subject" id="subject" required>
</div>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
<textarea name="message" placeholder="Your Message..." id="message"></textarea>
</div>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
<button class="theme-btn btn-style-one" onclick="javascript:SendMail()" type="submit" name="submit-form">Send Message</button>
</div>
</div>
</form>
when we click on the button the javascript function is called where i Called a webmethod which is in VisionMail.aspx.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function SendMail() {
var uname = document.getElementById("username").value;
var email = document.getElementById("email").value;
var phone = document.getElementById("phone").value;
var subject = document.getElementById("subject").value;
var message = document.getElementById("message").value;
var URL = "VisionMail.aspx?uname=" + uname + "&email=" + email + "&ph=" + phone + "&sub=" + subject + "&msg=" + message + "&count=India";
window.open(URL);
}
</script>
My WebMethod used for sending mail is in VisionMail.aspx as following:-
protected void Page_Load(object sender, EventArgs e)
{
string uname = Request.QueryString["uname"].ToString();
string email = Request.QueryString["email"].ToString();
string phone = Request.QueryString["ph"].ToString();
string subject = Request.QueryString["sub"].ToString();
string message = Request.QueryString["msg"].ToString();
string country = Request.QueryString["count"].ToString();
string close = #"<script type='text/javascript'>
window.returnValue = true;
window.close();
</script>";
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress("abc#gmail.com");
mail.To.Add("info#xyz.com");
mail.Subject = subject;
mail.Body = "Mr. " + uname + "<br/>" + "Email ID : " + email + " Phone No. " + phone + "<br/> <h4>He/She is Sending Message From Contact Page (" + country + "). <br/>" + message;
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
{
try
{
smtp.Credentials = new NetworkCredential("abc#gmail.com", "abc123");
smtp.EnableSsl = true;
smtp.Send(mail);
base.Response.Write(close);
}
catch (Exception ex)
{
base.Response.Write(close);
}
}
}
}
This code is well on local system and mail is going but when i publish it on server it does not work and when i click on button to send mail, the mail does not go and the page which the webmethod present is downloaded. Is there any solution for this.

Try with below code.
using (SmtpClient smtp = new SmtpClient("smtp.gmail.com"))
{
try
{
smtp.Credentials = new NetworkCredential("visioncomn#gmail.com", "visioncomptel123");
smtp.EnableSsl = smtp.Port == 587 || smtp.Port == 465;
smtp.Send(mail);
base.Response.Write(close);
}
catch (Exception ex)
{
base.Response.Write(close);
}
}

Related

Request Ajax failed getting http status 403

I am trying to save some store details and getting a response from the controller using Ajax but when I am trying to do so the request is not received by the Controller please see the code and help me what I am doing wrong here.
MasterAjaxClass: The class is used to send the request and receive a response
class MasterAjax{
constructor(){
this.requestType = null;
this.url = null;
this.timeout = 100000;
this.enctype = null;
this.data = null;
this.processData = null;
this.contentType = null;
this.responseData = null;
this.responseStatus = null;
this.responseStatusCode = null;
}
requestData(callBack){
var parameterError=false;
if(null == this.requestType){
parameterError=true;
console.log("Error: Request Type can't be null");
}
if(null === this.url || undefined === this.url || "undefined" === this.url){
parameterError=true;
console.log("Error: URL can't be null");
}
if(null == this.data || this.data.length <= 0){
//console.log("Warning: Data is null");
}
if(parameterError === false){
/*toggleSpinnerOn(); */
$.ajax({
type : this.requestType,
enctype : this.enctype,
processData : this.processData,
contentType : this.contentType,
// url : global_contextPath+"/"+this.url,
url : global_contextPath+"/"+this.url,
data: this.data,
timeout : this.timeout,
success : function(responseData,textStatus) {
/*toggleSpinnerOff();*/
callBack(responseData,textStatus);
},
error : function(responseData,textStatus) {
/*toggleSpinnerOff(); */
callBack(responseData,textStatus);
}
});
}
//return this.responseData;
}
}
Ajax Request method
function saveStore(){
let formData = new FormData();
//formData.append("key" , Value ) ;
formData.append("storeName", $("#storeName").val());
formData.append("country", $("#country").val());
formData.append("city", $("#city").val());
formData.append("street", $("#street").val());
formData.append("address", $("#address").val());
formData.append("zipCode", $("#zipCode").val());
formData.append("storeDescription", $("#storeDescription").val());
formData.append("storeOpenTime", $("#storeOpenTime").val());
formData.append("logoURL", $("#file-input-2").val());
console.log($("#storeName").val());
console.log($("#country").val());
console.log($("#city").val());
console.log($("#street").val());
console.log($("#address").val());
console.log($("#zipCode").val());
console.log($("#storeDescription").val());
console.log($("#storeOpenTime").val());
console.log($("#file-input-2").val());
var obj = new MasterAjax();
obj.requestType = "POST";
obj.url = "store/saveStore";
obj.data = formData;
obj.enctype ="multipart/form-data";
obj.contentType = false;
console.log("---------------------------")
for (var pair of formData.entries()) {
console.log(pair[0]+ ': ' + pair[1]);
}
console.log("---------------------------")
obj.requestData(function(responseData){
console.log(responseData);
if(responseData.status == "OK" || responseData.status == "ok"){
alert("success");
console.log(responseData)
}else{
alert(" failed");
console.log(responseData)
}
});
}
StoreForm.jsp
<form:form name="storeForms" modelAttribute="storeForm"
method="POST" enctype="multipart/form-data">
<%-- <c:if test="${not empty error}">
<div class="alert alert-danger" role="alert">
<h5 class="alert-heading">Failed to Save</h5>
<hr>
<p>${error}</p>
</div>
</c:if>
--%>
<!-- Hidden For Update employee -->
<form:input type="hidden" path="id" />
<!-- First row -->
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">Store Name</label>
<form:input type="text" path="storeName" class="form-control"
id="storeName" placeholder="Store Name" required="required" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Country</label>
<form:input type="text" id="country" path="country" class="form-control" />
</div>
</div>
<!-- Second row container -->
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">City</label>
<form:input type="text" id="city" path="city" class="form-control" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Street</label>
<form:input type="text" id="street" path="street" class="form-control" />
</div>
</div>
<!-- Third row container -->
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">Address</label>
<form:input type="text" id="address" path="address" class="form-control" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Zip Code</label>
<form:input type="text" id="zipCode" path="zipCode" class="form-control" />
</div>
</div>
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">Store Description</label>
<form:input type="text" path="storeDescription" id="storeDescription"
class="form-control" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Store Timings</label>
<form:input type="text" path="storeOpenTime" id="storeOpenTime" class="form-control" />
</div>
</div>
<div class="custom-file">
<form:input type="file" path="logoURL" id="file-input-2"
data-default-value="Size of logo should not Exeed 1mb" />
<label for="file-input-2">Choose logo</label>
</div>
<!-- Submit button container -->
<div class="text-right">
<!-- text-right = text-align: right -->
<input class="btn btn-primary" type="button" onclick="saveStore();" value="Add Store">
</div>
</form:form>
Controller Method
#Controller
#RequestMapping("/store")
public class StoreController {
#ResponseBody
#RequestMapping(value = "/saveStore" , method = {RequestMethod.POST},consumes = {"multipart/form-data"})
public APIResponseModal saveStore(#ModelAttribute("storeForm") StoresDTO store,#RequestPart("logoURL") MultipartFile file) {
logger.info("Store Save MEthod callled !!!!!!!!");
Stores storeModal = new Stores();
String logopath = "";
APIResponseModal apiResponse = new Utils().getDefaultApiResponse();
List<String> errorList = new ArrayList<String>();
try {
if(store !=null){
storeModal = new Stores(store);
if(!file.isEmpty()) {
if(file.getSize()>1000000) {//1000000 bytes == 1 mb
errorList.add("File size should be less than 1 MB");
}
logopath = Utils.storeLogoPath(file);
}
storeService.saveStore(storeModal, errorList,logopath);
if(errorList.isEmpty() && !Utils.isNotNull(errorList)) {
apiResponse.setStatus(HttpStatus.OK);
apiResponse.setData("--");
apiResponse.setMessage("Store Saved Successfully !!");
}else {
apiResponse.setMessage("Failed to save store !!");
apiResponse.setStatus(HttpStatus.BAD_REQUEST);
}
}
} catch (Exception e) {
e.printStackTrace();
apiResponse.setStatus(HttpStatus.BAD_REQUEST);
apiResponse.setData("--");
apiResponse.setMessage("Error Occured at our end !!");
}
logger.info("API RESPONSE:: ::"+ apiResponse);
return apiResponse;
}
}
Error On browser Console
Status :403

Cannot submit form with the usage of Ajax in ASP.NET MVC

I have an issue about submitting a form via ajax and open a modal Dialog after the ajax function is completed successfully. When I click a submitButton, the process cannot be completed.
Where is the problem in an ajax method or anywhere?
How can I fix it?
Here is my form HTML part.
<form id="contactForm" role="form" class="php-email-form">
#Html.AntiForgeryToken()
<div class="row">
<div class="col-md-6 form-group">
<input type="text" name="nameSurname" class="form-control" id="nameSurname" placeholder="Name Surname" required>
</div>
<div class="col-md-6 form-group mt-3 mt-md-0">
<input type="email" class="form-control" name="email" id="email" placeholder="Email" required>
</div>
</div>
<div class="form-group mt-3">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" required>
</div>
<div class="form-group mt-3">
<textarea class="form-control" name="message" id="message" rows="5" placeholder="Message" required></textarea>
</div>
<div class="my-3"></div>
<div class="text-center">
<button type="submit" id="submitButton" data-bs-toggle="modal">Submit</button> <!-- data-bs-target="#modalDialog"-->
</div>
</form>
Here is my modal part.
<div class="modal fade" id="modalDialog" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
#ViewBag.Success
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-bs-dismiss="modal">Kapat</button>
</div>
</div>
</div>
</div>
Here is my javascript part.
<script type="text/javascript">
$(document).ready(function () {
$("#submitButton").click(function () {
var nameSurname = $("#nameSurname").val();
var email = $("#email").val();
var subject = $("#subject").val();
var message = $("#message").val();
var form = $('#contactForm');
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
url: '/Home/Contract/',
data: {
__RequestVerificationToken: token,
nameSurname: nameSurname, email: email, subject: subject, message: message
},
type: 'POST',
success: function (data) {
$("#modalDialog").show();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('custom message. Error: ' + errorThrown);
}
});
});
})
</script>
Here is my Contract action in Home Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Contract(string nameSurname = null, string email = null, string subject = null, string message = null)
{
if (nameSurname != null && email != null)
{
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com");
smtpClient.Port = 587;
smtpClient.Credentials = new System.Net.NetworkCredential("gmail address", "gmail address password");
// smtpClient.UseDefaultCredentials = true; // uncomment if you don't want to use the network credentials
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = message;
//Setting From , To and CC
mail.From = new MailAddress(email);
mail.To.Add(new MailAddress("gmail address"));
smtpClient.Send(mail);
ViewBag.Success = "Success";
}
else
{
ViewBag.Error = "Error";
}
return View();
}
EDIT
After I realized Ok() isn’t accessible in an MVC controller I found this solution which does essentially the same thing.
In your controller, change:
return RedirectToAction(“contract”);
To:
return new HttpStatusCodeResult(HttpStatusCode.OK);
RedirectToAction() and View() will by default load or refresh a page while a 200 (OK) response will just return a success status code.
You can do it this way:
View:
#using (Ajax.BeginForm("Contract", "ControllerName", FormMethod.Post, new AjaxOptions { HttpMethod = "POST", OnBegin = "OnBegin", OnSuccess = "OnSuccess", OnFailure = "OnFailure" }, new { #id = "ajaxForm" }))
{
<div class="card">
<div class="card-body">
#Html.AntiForgeryToken()
<div class="row">
<div class="col-md-6 form-group">
<input type="text" name="nameSurname" class="form-control" id="nameSurname" placeholder="Name Surname" required>
</div>
<div class="col-md-6 form-group mt-3 mt-md-0">
<input type="email" class="form-control" name="email" id="email" placeholder="Email" required>
</div>
</div>
<div class="form-group mt-3">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" required>
</div>
<div class="form-group mt-3">
<textarea class="form-control" name="message" id="message" rows="5" placeholder="Message" required></textarea>
</div>
<div class="my-3"></div>
<div class="text-center">
<button type="submit" id="submitButton">Submit</button> <!-- data-bs-target="#modalDialog"-->
</div>
</div>
</div>
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Contract(string nameSurname = null, string email = null, string subject = null, string message = null)
{
// do what is necessary
if (nameSurname != null && email != null)
{
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com");
smtpClient.Port = 587;
smtpClient.Credentials = new System.Net.NetworkCredential("gmail address", "gmail address password");
// smtpClient.UseDefaultCredentials = true; // uncomment if you don't want to use the network credentials
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = message;
//Setting From , To and CC
mail.From = new MailAddress(email);
mail.To.Add(new MailAddress("gmail address"));
smtpClient.Send(mail)
return Json("Success", JsonRequestBehavior.AllowGet);
}
else // return result
{
return Json("Error", JsonRequestBehavior.AllowGet);
}
}
We have to create OnSuccess function in view to do something with result;
<script>
function OnSuccess(data) {
if (data == 'Success') {
$("#modalDialog").modal('show');
}
}
function OnFailure(data) {
//log failure
}
function OnBegin() {
// do something on begin
}
</script>

How to display a JasperReports pdf file in an iframe?

in currently I run my pdf report using JasperReports when clicking on report button the pdf report run with another browser tab but now I want to run the report on my JSP page using iframe tag. please help me to view / embedded jasper report on my web page.................................
everybody can give me an example.
Html code is
<div class="col-md-12">
<!-- begin panel -->
<div class="panel panel-inverse" data-sortable-id="form-stuff-2">
<div class="panel-heading">
<div class="panel-heading-btn">
<i class="fa fa-expand"></i>
</div>
<h4 class="panel-title">Ship Service Report Page </h4>
</div>
<div class="panel-body">
<form class="form-horizontal">
<div class="form-group">
<label class="col-md-2 control-label">Ship Name</label>
<div class="col-md-4">
<select name="" class="form-control" id="shipNam" name="shipNam">
<option value="" selected="selected">Select Ship name</option>
<s:iterator value="reportInfos" status="rowstatus">
<option value="<s:property value='shipNo' />"><s:property value='shipName' /></option>
</s:iterator>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">From Date</label>
<div class="col-md-3">
<input type="text" class="form-control" name="fromDate" id="fromDate" placeholder="Select Date" value="" />
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">To Date</label>
<div class="col-md-3">
<input type="text" class="form-control" name="toDate" id="toDate" placeholder="Select Date" value="" />
</div>
</div>
<div class="form-group col-md-6">
<label class="col-md-4 control-label">Report Format</label>
<div class="col-md-8">
<label class="radio-inline">
<input type="radio" name="optionsRadios" id="option1" value="pdf" checked />
PDF
</label>
<label class="radio-inline">
<input type="radio" name="optionsRadios" id="option2" value="xls" />
Excel
</label>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<button type="button" class="btn btn-sm btn-success" onclick="getShipServiceReport('shipNam','toDate' , 'fromDate')">View</button>
</div>
</div>
</form>
</div>
</div>
<!-- end panel -->
</div>
my js function/report calling function
function getShipServiceReport(ship_no,to_date, fromDate){
var shipNos=document.getElementById(ship_no).value;
var toDate=document.getElementById(to_date).value;
var fromDate=document.getElementById(fromDate).value;
var fileType=$('input[name="optionsRadios"]:checked').val();
var ajaxURL = "getShipServiceReportRT.do?ship_no="+shipNos+"&to_date="+toDate+"&fileType="+fileType+"&fromDatee="+fromDate;
window.open(ajaxURL,'_blank');
//$("#documentArea.html('<iframe src='"+ajaxURL+"' frameBorder='0' style='height:1200px;width:100%;'></iframe>')");
}
Java Action class
public void getShipServiceReport()throws JRException, ServletException, IOException{
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("shipNo", ship_no);
parameters.put("fromDate", fromDatee);
parameters.put("toDate", to_date);
System.out.println("Parameter"+ship_no);
String filename="shipServiceInformation.jasper";
String reportType=fileType;
showReport("",parameters,filename,reportType);
}
public static void showReport(String key, Map<String, Object> parameters, String filename, String reportType)
throws JRException, ServletException, IOException {
Connection connection = null;
HttpServletResponse response = ServletActionContext.getResponse();
String outputFileName = "report_" + key;
connection = DBC.openCon();
ServletContext context = ServletActionContext.getServletContext();
String path = context.getRealPath("/");
JasperPrint jasperPrint = JasperFillManager.fillReport(path + "jasper" + "/" + filename, parameters,
connection);
OutputStream ouputStream = response.getOutputStream();
JRExporter exporter = null;
if ("pdf".equalsIgnoreCase(reportType)) {
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "inline;filename=" + outputFileName + "." + reportType);
exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
System.out.println("Report Created");
} else if ("rtf".equalsIgnoreCase(reportType)) {
response.setContentType("application/rtf");
response.setHeader("Content-disposition", "inline;filename=" + outputFileName + "." + reportType);
exporter = new JRRtfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
} else if ("html".equalsIgnoreCase(reportType)) {
exporter = new JRHtmlExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
} else if ("xls".equalsIgnoreCase(reportType)) {
response.setContentType("application/xls");
response.setHeader("Content-disposition", "inline;filename=" + outputFileName + "." + reportType);
exporter = new JRXlsExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
} else if ("csv".equalsIgnoreCase(reportType)) {
response.setContentType("application/xls");
response.setHeader("Content-disposition", "inline;filename=" + outputFileName + "." + reportType);
exporter = new JRCsvExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
}
try {
// JasperViewer.viewReport(jasperPrint, true); // for direct print
exporter.exportReport();
} catch (JRException e) {
System.out.println(e);
} finally {
if (ouputStream != null) {
try {
ouputStream.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
just add this line in js function instate of "window.open(ajaxURL,'_blank');" line
$('#documentArea').html("<iframe name='your_frame_name' src='"+ajaxURL+"' height=100% width=100% > </iframe>")

How to find directories within the directory the index.html file is stored within using Javascript?

I'm using an input box, when the search button is pressed I want to see if the searched term is an existing directory within the directory that the index.html file is stored within. Here's the code so far:
function searchWebs () {
var searchedTermRaw = document.getElementById('searchBox').value;
var searchedTerm = searchedTermRaw.toUpperCase();
if (searchedTerm == "") {
return;
} else {
if (searchedTerm == "NUMI" || searchedTerm == "ELMDON PM") {
document.getElementById('searchFor').innerHTML = "Search results for '" + searchedTermRaw + "'.";
document.getElementById('searchForDetails').innerHTML = "";
} else {
document.getElementById('searchFor').innerHTML = "No search results were found for '" + searchedTermRaw + "'.";
document.getElementById('searchForDetails').innerHTML = "Please use the ID provided within the email Netwal sent you, if you have not been sent an email with the ID, your website isn't ready for viewing/testing yet.";
}
}
}
<div class="section">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="col-sm-12">
<input type="text" class="form-control input-lg" id="searchBox" placeholder="Website ID">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<br>
<a class="btn btn-lg btn-primary col-lg-12" onclick="searchWebs();">Search</a>
</div>
</div>
</div>
</div>
<div class="section">
<div class="container">
<div class="row">
<div class="col-md-12">
<h1 id="searchFor"></h1>
<p id="searchForDetails"></p>
</div>
</div>
</div>
</div>
I want to replace the if statement for checking if the search term is NUMI or ELMDON PM with checking if the directory exists.
Use this method isAvailable(url) and pass the path or searchedTerm
Make sure to maintain the cross-origin policy.
I have added baseUrl as https://stacksnippets.net/ for that issue.
var baseUrl = "https://stacksnippets.net/";
function isAvailable(url) {
url = baseUrl + url;
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
try {
http.send();
} catch (err) {
return false;
}
return http.status != 404;
}
EXAMPLE:
I tried term js which will produce url https://stacksnippets.net/js
I am afraid the example will not work due to cross-origin and mixed-content errors but this approach should work in your case.
You can check for your resource in your domain by changing the baseUrl
SNIPPET
function searchWebs() {
var searchedTermRaw = document.getElementById('searchBox').value;
var searchedTerm = searchedTermRaw.toUpperCase();
if (searchedTerm == "") {
return;
} else {
if (isAvailable(searchedTerm)) {
document.getElementById('searchFor').innerHTML = "Search results for '" + searchedTermRaw + "'.";
document.getElementById('searchForDetails').innerHTML = "";
} else {
document.getElementById('searchFor').innerHTML = "No search results were found for '" + searchedTermRaw + "'.";
document.getElementById('searchForDetails').innerHTML = "Please use the ID provided within the email Netwal sent you, if you have not been sent an email with the ID, your website isn't ready for viewing/testing yet.";
}
}
}
var baseUrl = "https://stacksnippets.net/";
function isAvailable(url) {
url = baseUrl + url;
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
try {
http.send();
} catch (err) {
return false;
}
return http.status != 404;
}
<div class="section">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="col-sm-12">
<input type="text" class="form-control input-lg" id="searchBox" placeholder="Website ID">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<br>
<a class="btn btn-lg btn-primary col-lg-12" onclick="searchWebs();">Search</a>
</div>
</div>
</div>
</div>
<div class="section">
<div class="container">
<div class="row">
<div class="col-md-12">
<h1 id="searchFor"></h1>
<p id="searchForDetails"></p>
</div>
</div>
</div>
</div>

Username checking not working for form with multiple register models (mvc)

I have a page which allows an admin to add multiple users to the database at once, with usernames and passwords. I use remote username checking, so in my account models I have this:
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
[System.Web.Mvc.Remote("doesUserNameExist", "Account", HttpMethod = "POST", ErrorMessage = "User name already exists. Please enter a different user name.")]
public string UserName { get; set; }
// ...etc
}
In my account controller I have this:
[HttpPost]
public JsonResult doesUserNameExist(string UserName)
{
var user = Membership.GetUser(UserName);
return Json(user == null);
}
Now this works nicely on a single form, with one user being created, using the mvc html helpers. The message saying that a username is in use shows up as I'm typing it into the field. But on this form which doesn't use the mvc helpers, instead pure html and javascript, it doesn't show up:
#model List<PicsWebApp.Models.UserRegisterModel>
#{
ViewBag.Title = "NewRep";
}
<div class="col-lg-12">
<h1>First-Time Setup</h1>
</div>
<legend></legend>
<div class="col-lg-12">
<h3>Add Representatives <small>You can add more representatives later</small></h3>
#using (Html.BeginForm("NewRep", "Admin", new { jobid = ViewData["jobid"] }, FormMethod.Post, new { #class = "form" }))
{
#Html.ValidationSummary(true)
<p>
Skip
<input type="submit" class="btn btn-primary" />
<button type="button" class="btn btn-default" id="add">Add Rep</button>
</p>
<div id="fieldform" class="col-lg-12">
<div id="container0" class="col-lg-4" style="background-color: #eee; border: 4px solid white;">
<h4 style="text-align: center">New Rep</h4>
<div class="form-group">
<label>Representative Name</label><input type="text" class="form-control" name="models[0].RepName" />
</div>
<div class="form-group">
<label>Contact Number</label><input type="text" class="form-control" name="models[0].ContactNumber" />
</div>
<div class="form-group">
<label>Rep Username</label><input type="text" class="form-control" name="models[0].UserName" />
<input class="text-box single-line" data-val="true" data-val-remote="User name already exists. Please enter a different user name." data-val-remote-additionalfields="*.UserName" data-val-remote-type="POST" data-val-remote-url="/Account/doesUserNameExist" data-val-required="The User name field is required." id="UserName" name="models[0].UserName" type="text">
<span class="field-validation-valid" data-valmsg-for="UserName" data-valmsg-replace="true"></span>
</div>
<div class="form-group">
<label>Location</label><select id="select-0" class="form-control" name="models[0].Location"></select>
</div>
<div class="form-group">
<label>Rep Password</label><input type="password" class="form-control" name="models[0].Password" />
</div>
<div class="form-group">
<label>Confirm Password</label><input type="password" class="form-control" name="models[0].ConfirmPassword" />
</div>
</div>
</div>
}
</div>
<script src="https://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
var selectValues = {
"Johannesburg": "Johannesburg",
"Pretoria": "Pretoria",
"Cape Town": "Cape Town",
"Pretoria": "Pretoria",
"Durban": "Durban",
"Centurion": "Centurion"
};
$.each(selectValues, function (key, value) {
$('select')
.append($('<option>', { value: key })
.text(value))
.prop("selectedIndex", -1);
});
var i = 1;
$("#add").click(function () {
var inputfield = '<div class="col-lg-4" id="' + container + i + '" style="background-color: #eee; border: 4px solid white;"><h4 style="text-align: center">New Rep</h4><div class="form-group"><label>Representative Name</label><input type="text" class="form-control" name="models[' + i + '].RepName" /></div>' +
'<div class="form-group"><label>Contact Number</label><input type="text" class="form-control" name="models[' + i + '].ContactNumber" /></div>' +
'<div class="form-group"><label>Rep Username</label><input type="text" class="form-control" name="models[' + i + '].UserName" /></div>' +
'<div class="form-group"><label>Location</label><select id="select-' + i + '" class="form-control" name="models[' + i + '].Location"></select></div>' +
'<div class="form-group"><label>Rep Password</label><input type="password" class="form-control" name="models[' + i + '].Password" /></div>' +
'<div class="form-group"><label>Confirm Password</label><input type="password" class="form-control" name="models[' + i + '].ConfirmPassword"/></div></div>'
$('#fieldform').append(inputfield)
$.each(selectValues, function (key, value) {
$('#select-' + i)
.append($('<option>', { value: key })
.text(value))
.prop("selectedIndex", -1);
});
i++
});
</script>
I understand I would have to add validation attributes to the username input fields but I tried that and it still didn't work. Any ideas?
You could validate in your controller (when the ajax request is sent) using the Validator class. This class allows you to call Validator.TryValidateObject to validate your model's data annotations such as [Required].
Then once this has passed/failed return the constructed json data with success/error messages.
Here is the article that really helped me on this:
http://odetocode.com/blogs/scott/archive/2011/06/29/manual-validation-with-data-annotations.aspx

Categories