Spring Boot - JQuery AJAX not doing anything - javascript

Hello I am facing problems with doing my first webclient working with jquery AJAX JSON
Actually if I am pressing submit at my webclient to add a contact to a contact List it is not doing anything for me someone can help me here?
If am using postman to send a request it is working but the informations doesnt display in the index (videolist [html]) it is just showing as usual text in
/url/{id}
This is my HTML
<!DOCTYPE html>
<html>
<head>
<title>Contact Archiv HTML</title>
<meta charset="utf-8">
<link rel="stylesheet" href="css/styles.css">
<link rel="stylesheet"
href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script type="text/javascript"
src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js">
</script>
<script type="text/javascript" src="ajaxfunctions.js"></script>
</head>
<body>
<div class="centerdiv">
<header><h1>Video Archiv</h1></header>
<section class="left">
<h1>Neues Video anlegen</h1>
<p>
<form id="newVideo">
<label>id:</label>
<input type="text" name="id" required="required" >
<label>vorname:</label>
<input type="text" name="vorname" required="required" >
<label>nachname:</label>
<input type="text" name="nachname" required="required" >
<label>anrede:</label>
<input type="text" name="anrede" required="required" >
<label>adresse:</label>
<textarea name="adresse" required="required" rows="10"></textarea>
<label>telefon:</label>
<input type="text" name="telefon" required="required">
<label>email:</label>
<input type="text" name="email" required="required">
<label>handy:</label>
<input type="text" name="handy" required="required" >
<br>
<input type="submit" id="newVideoButton">
</form>
</p>
</section>
<section class="right">
<h1>Meine Videos</h1>
<p>
<button id="loadtable">Laden</button>
<table id="videotable" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>id</th>
<th>vorname</th>
<th>nachname</th>
<th>anrede</th>
<th>adresse</th>
<th>telefon</th>
<th>email</th>
<th>handy</th>
</tr>
</thead>
</table>
</p>
</section>
<footer>Tested</footer>
</div>
</body>
</html>
This is my ajaxfunction:
//On Page load - register listeners and load existing videos in datatable
$(document).ready(function() {
loadDataTable();
//process the form newVideo
$("#newVideo").submit(function(event) {
postVideo(event);
});
//Load Datatable
$('#loadtable').click(function() {
loadDataTable();
});
});
function postVideo(event) {
// get the form data
var formData = {
'id' : $('input[name=id]').val(),
'vorname' : $('textarea[name=vorname]').val(),
'nachname' : $('input[name=nachname]').val(),
'anrede' : $('input[name=anrede]').val()
'adresse' : $('input[name=adresse]').val(),
'telefon' : $('textarea[name=telefon]').val(),
'email' : $('input[name=email]').val(),
'handy' : $('input[name=handy]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to
use (POST for our form)
contentType : 'application/json',
url : '/kontakte', // url where we want to POST
data : JSON.stringify(formData), // data we want to POST
success: function( data, textStatus, jQxhr ){
loadDataTable();
},
error: function( jqXhr, textStatus, errorThrown ){
console.log(errorThrown);
}
});
// stop the form from submitting the normal way and refreshing the
page
event.preventDefault();
}
function loadDataTable() {
var table = $('#videotable').DataTable({
destroy: true,
"ajax": {
"url": "/kontakte", //URL
"dataSrc": "" // Cause of flat JsonObjects
},
"columns": [
{ "data": "id" },
{ "data": "vorname" },
{ "data": "nachname" },
{ "data": "anrede" },
{ "data": "adresse" },
{ "data": "telefon" },
{ "data": "email" },
{ "data": "handy"}
]
});
}
Class Contact:
package RestPackage;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
public class Kontakte {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String vorname;
private String nachname;
private String anrede;
private String adresse;
private String telefon;
private String email;
private String handy;
public Kontakte() {}
public Kontakte(int id, String vorname, String nachname, String anrede,
String adresse, String telefon, String email, String handy) {
super();
this.id = id;
this.vorname = vorname;
this.nachname = nachname;
this.anrede = anrede;
this.adresse = adresse;
this.telefon = telefon;
this.email = email;
this.handy = handy;
}
public long getID() {
return id;
}
public void setID(int id) {
this.id = id;
}
public String getVorname() {
return vorname;
}
public void setVorname(String vorname) {
this.vorname = vorname;
}
public String getNachname() {
return nachname;
}
public void setNachname(String nachname) {
this.nachname = nachname;
}
public String getAnrede() {
return anrede;
}
public void setAnrede(String anrede) {
this.anrede = anrede;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public String getTelefon() {
return telefon;
}
public void setTelefon(String telefon) {
this.telefon = telefon;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getHandy() {
return handy;
}
public void setHandy(String handy) {
this.handy = handy;
}
}
My Controller:
package RestPackage;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import RestPackage.Kontakte;
#RestController
public class VerwaltungsController {
#Autowired
VerwaltungsService verwaltungsService;
#RequestMapping ("/kontakte")
public List<Kontakte> getKontakteList(){
return verwaltungsService.getKontakteList();
}
#RequestMapping("/kontakte/{id}")
public Kontakte getKontakt(#PathVariable Integer id) {
return verwaltungsService.getKontakt(id);
}
#RequestMapping(method=RequestMethod.POST, value="/kontakte")
public void addKontakt(#RequestBody Kontakte k) {
verwaltungsService.addKontakt(k);;
}
#RequestMapping(method=RequestMethod.PUT, value="/kontakte/{id}")
public void updateKontakt(#PathVariable Integer id, #RequestBody Kontakte
kontakt) {
verwaltungsService.updateKontakt(id, kontakt);
}
#RequestMapping(method=RequestMethod.DELETE, value="/kontakte/{id}")
public void deleteKontakt(#PathVariable Integer id) {
verwaltungsService.deleteKontakt(id);
}
}
Service Class:
package RestPackage;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import RestPackage.Kontakte;
#Service
public class VerwaltungsService {
#Autowired
private KontakteRepository kontakteRepository;
public List<Kontakte> getKontakteList() {
ArrayList<Kontakte> mylist= new ArrayList<>();
Iterator<Kontakte> it = kontakteRepository.findAll().iterator();
while(it.hasNext())
mylist.add(it.next());
return mylist;
}
public Kontakte getKontakt(#PathVariable Integer id) {
return kontakteRepository.findOne(id);
}
public void addKontakt(#RequestBody Kontakte kontakt) {
kontakteRepository.save(kontakt);
}
public void updateKontakt(#PathVariable Integer id, #RequestBody Kontakte
kontakt) {
Kontakte k = kontakteRepository.findOne(id);
k.setVorname(kontakt.getVorname());
k.setNachname(kontakt.getNachname());
k.setAdresse(kontakt.getAdresse());
k.setAnrede(kontakt.getAnrede());
k.setEmail(kontakt.getEmail());
k.setHandy(kontakt.getHandy());
k.setTelefon(kontakt.getTelefon());
kontakteRepository.save(k);
}
public void deleteKontakt(#PathVariable Integer id) {
kontakteRepository.delete(id);
}
}
CrudRep. Interface:
package RestPackage;
import org.springframework.data.repository.CrudRepository;
import RestPackage.Kontakte;
public interface KontakteRepository extends CrudRepository<Kontakte,
Integer> {
}

There is , missing in the mapping of the input properties. I also advice you to start using the console (key F12) to debug the code and discover problems easly.

Related

Asp.net Core PartialView submits form unnecessarily

I want to create a Quiz website with Asp. I want to create Quiz, add questions to the quiz, and add answers to the question. Add question button adds a question, but the Addanswer button submits the form instead of adding an answer to the question.
My classes:
public class Answer
{
[Key]
public Guid Id { get; } = Guid.NewGuid();
public string Content { get; set; }
public Guid QuestionId { get; set; }
public class Question
{
[Key]
public Guid Id { get; } = Guid.NewGuid();
public string Content { get; set; }
public Guid QuizId { get; set; }
public ICollection<Answer> Answers { get; set; } = new List<Answer>() {
new Answer() { Content = "Answeeeer" },
new Answer() { Content = "Answeeeer2" },
new Answer() { Content = "Answeeeer3" }
};
public class Quiz
{
[Key]
public Guid Id { get; } = Guid.NewGuid();
public string Name { get; set; }
public ICollection<Question> Questions { get; set; } = new List<Question>() { };
In front side I have Question and Answer Partial views:
Question Partial View:
#model QuizIt_Tests.Entities.Question
<hr style="height: 4px; color: black;" />
<div class="w-100 p-3 px-5 my-3">
<label asp-for="Content" class="control-label">Question</label>
<input asp-for="Content" class="form-control" value="#Model.Content" />
<span asp-validation-for="Content" class="text-danger"></span>
<div id="answerRows #Model.Id" class="w-75">
#Html.EditorFor(model => model.Answers)
<button class="btn btn-primary" id="addAnswer #Model.Id">Add Answer</button>
</div>
</div>
#section Scripts {
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="jquery-3.6.1.min.js"></script>
<script>
$("#addAnswer " + #Model.Id).click(function () {
console.log("clicked");
$.ajax({
url: '#Url.Action("AddBlankQuestion", "Quizes")',
cache: false,
success: function (html) {
$("#answerRows " + #Model.Id").append(html); },
error: function (xhr, status, error) {
console.log(xhr.responseText);
}
});
return false;
});
</script>
}
Answer Partial View:
#model QuizIt_Tests.Entities.Answer
<div class="row" style="background-color:red; margin: 20px;">
<label asp-for="Content" class="control-label">Answer Content</label>
<input asp-for="Content" class="form-control" value="#Model.Content" />
<span asp-validation-for="Content" class="text-danger"></span>
</div>
My Controller:
public class QuizesController : Controller
{
private readonly ApplicationDBContext _context;
public QuizesController(ApplicationDBContext context)
{
_context = context;
}
public IActionResult AddBlankQuestion(Quiz model)
{
Question question = new Question();
return PartialView("EditorTemplates/Question", question);
}
public IActionResult AddBlankAnswer(Question model)
{
return PartialView("EditorTemplates/Answer", new Answer() { QuestionId = model.Id });
}
}
You did not specify the type attribute in the button, which by default is equal to submit which causes the form to be submitted, to change its behavior, change the type value to button as follows.
<button type="button" class="btn btn-primary" id="addAnswer #Model.Id">Add Answer</button>

How to pass data between views and controller?

This is our Home Index:
#model ELearning.Data.ELearningEgitimDTO
#{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
#if (TempData["message"] != null)
{
<div class="alert alert-info" role="alert">#TempData["message"]</div>
}
<div>
<div>
#if (Model.EgitimTuru == 5)
{
<h1>Yangın Eğitimi</h1>
}
<table class="table table-responsive">
<tr>
<td width="20%">Şirket Adı:</td>
<td width="80%">#Model.Name</td>
</tr>
<tr>
<td>Eğitimi Veren:</td>
<td>#Model.PersonelAdi</td>
</tr>
<tr>
<td>Eğitim Tarihi:</td>
<td>#Model.Tarih</td>
</tr>
</table>
</div>
<div>
<table class="table table-responsive">
<tr>
<td>Eğitim Konuları:</td>
</tr>
#foreach (var konu in Model.Adi)
{
<tr>
<td><ul><li>#konu</li></ul></td>
</tr>
}
</table>
</div>
</div>
<p class="text-right"><button onclick="getStartDate()" class="btn btn-primary btn-lg ">Eğitime Başla »</button></p>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
function getStartDate() {
$.post("/Video/GetStartDate",
{
PerNr: #Model.PerNr,
StartDate: "",
EndDate: "",
EgitimFilesId: #Model.FileId
});
}
</script>
</div>
This is Video Index:
#model WebApplication3.Models.VideoLogsModel
#{
ViewBag.Title = "Video Page";
}
<div class="jumbotron">
<div>Eğitime başlanan zaman:</div>
<div id="startdate"></div>
<div class="col-md-12 text-center">
<video controls controlslist="nodownload" id="videoPlayer" width: 100% height: auto>
<source src="~/Video/GetVideo" type="video/mp4">
</video>
</div>
<br />
<div class="text-right">
<p id="button" onclick="egitimiBitir()" class="btn btn-danger btn-lg ">Eğitimi Bitir</p>
</div>
<script type="text/javascript">
var vid = document.getElementById("videoPlayer");
var button = document.getElementById("button");
if (vid.played) {
setInterval(function () { vid.pause(); }, 30000);
}
vid.addEventListener("ended", function() {
button.className = "btn btn-success btn-lg "
});
function egitimiBitir() {
if (vid.ended) {
$.post("/Video/GetEndDate",
{
PerNr: #Model.PerNr,
StartDate= "",
EndDate: "",
EgitimFile sId: #Model.EgitimFilesId
});
}
else {
document.getElementById("message").innerHTML = "Video tamamlanmadan eğitimi bitiremezsiniz.."
}
}
</script>
</div>
This is our main model:
public class ELearningEgitimDTO
{
public ELearningEgitimDTO() { }
public ELearningEgitimDTO(string PerNr, int ID)
{
this.ID = ID;
this.PerNr = PerNr;
}
public int ID { get; set; }
public string PerNr { get; set; }//katılımcıID
public string Name { get; set; }//şirket adı
public int EgitimTuru { get; set; }
public DateTime Tarih { get; set; }//egitim tarihi
public string PersonelAdi { get; set; } // eğitimi veren
public int FileId { get; set; }
public string FileName { get; set; }
public string[] Adi { get; set; }
}
This is our model:
public class VideoLogsModel
{
public int EgitimFilesId { get; set; }
public int PerNr { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
This is our Home Controller:
public class HomeController : Controller
{
public ActionResult Index(int EgitimId=4, string PerNr="2")
{
ELearningService service = new ELearningService();
ELearningEgitimDTO egitim = new ELearningEgitimDTO(PerNr, EgitimId);
return View(service.getInfo(egitim)); //eğitim bilgileri istenirken egitimId ve egitim kullanıcıdaki eğitmenin perNr si verilmeli!!
}
}
This is our Video Controller:
public class VideoController : Controller
{
public ActionResult Index(VideoLogsModel model)
{
return View(model);
}
public ActionResult GetVideo()
{
var memoryStream = new MemoryStream(System.IO.File.ReadAllBytes(#"C:\Users\cyare\Desktop\videoplayback.mp4"));
//byte[] bytes = System.IO.File.ReadAllBytes(#"C:\Users\melik.DESKTOP-LQQAB68\Desktop\videoplayback.mp4");
//System.IO.File.WriteAllBytes(#"C:\Users\melik.DESKTOP-LQQAB68\Desktop\videoplayback.mp4", bytes);
return new FileStreamResult(memoryStream, "video/mp4");
}
/* [HttpPost]
public ActionResult GetStartEndDate(VideoLogsModel logs)
{
DateTime startDate = logs.StartDate; //database de uygun tabloya yazılır
return RedirectToAction("Index", "Video");
}*/
[HttpPost]
public ActionResult GetStartDate(VideoLogsModel model)
{
model.StartDate = System.DateTime.Now;
ELearningDosyaKullaniciDTO user = new ELearningDosyaKullaniciDTO();
user.egitimFileID = model.EgitimFilesId;
user.egitimKullanıcı = model.PerNr;
user.startDate = model.StartDate;
ELearningService service = new ELearningService();
//service.CreateLogs(user);
//return RedirectToAction("Index","Video",model);*/
return RedirectToAction("Index", model);
}
[HttpPost]
public ActionResult GetEndDate(VideoLogsModel model)
{
model.EndDate = System.DateTime.Now;
ELearningDosyaKullaniciDTO user = new ELearningDosyaKullaniciDTO();
user.egitimFileID = model.EgitimFilesId;
user.egitimKullanıcı = model.PerNr;
user.endDate = model.EndDate;
ELearningService service = new ELearningService();
service.UpdateLogs(user);
TempData.Add("message", String.Format("Eğitiminiz Tamamlanmıştır!"));
return RedirectToAction("Index", "Home");
}
}
My question is how can i pass the model from home index to video controller and then to video index?
Video Index doesn't run. It goes to video index but then it runs home index again.
Also it runs egitimibitir() function before button's onclick function.
You send an ajax request to your service. (endpoint => GetEndDate) I think you can change your code like that,
$.ajax({
type: "POST",
url: "/Video/GetEndDate", //your reqeust url
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
// your data here
}),
success: function (data) {
// check state of data
// after check window.location = // redirect url
},
error: function (data) {
// handle exception
}
});
You can change your controller method to a data controller. (not an ActionResult. create a custom result object which include your data and your success state. you can use this custom result object every ajax requests for return state and data). If an exception occurs while executing "GetEndDate" method, you need to handle exception and you need to show it to client. You send exception or your success complete response to to client(view). (you can handle your exception data in ajax error: function)

No Success With Angular 2 Http Post to .Net Core Web Api 2

Been beating my head on this for a day. Just trying to make a simple POST to a .Net Core Web Api 2 service from Angular.
I'm using the Angular SPA template that can be downloaded for Visual Studio 2017 I found from this tutorial
Everything I'm reading online says the same thing, which I have done here as exactly as I can. No matter what I try, my Angular method isn't even hitting my Api method. I've been staring at this for so long, I'm pretty sure I'm missing something, but I can't see it.
Angular makes it very easy to do Http GETs, but I'm learning that POSTs are a pain in the ass to figure out.
Api Method
[HttpPost(Name = "AddSample")]
public IActionResult AddSample([FromBody]Sample sample)
{
var result = _repository.AddSample(sample);
if (sample.SampleId == 0)
{
return BadRequest();
}
return Ok();
}
Api Sample Model
public class Sample
{
public int SampleId { get; set; }
public string Barcode { get; set; }
public DateTime CreatedAt { get; set; }
public int CreatedBy { get; set; }
public int StatusId { get; set; }
}
Angular Component Html
<div class="panel panel-primary">
<div class="panel-heading">
<h1>Add Sample</h1>
</div>
<div class="panel-body">
<div class="form-group">
<label class="control-label">Barcode</label>
<input type="text" class="form-control" [(ngModel)]="barCode" />
</div>
<div class="form-group">
<label class="control-label">Created By</label>
<select class="form-control" [(ngModel)]="createdBy">
<option *ngFor="let user of users" value={{user.userId}}>
{{ user.firstName + " " + user.lastName }}
</option>
</select>
</div>
<div class="form-group">
<label class="control-label">Status</label>
<select class="form-control" [(ngModel)]="statusId">
<option *ngFor="let status of statuses" value={{status.statusId}}>
{{ status.statusTxt }}
</option>
</select>
</div>
<input type="submit" class="btn btn-danger" value="Submit" (click)="addSample(barCode, createdBy, statusId)"/>
</div>
Angular TypeScript File
import { Component } from '#angular/core';
import { Http, Response, Headers, Request, RequestOptions } from '#angular/http';
import { SampleModel } from '../../../models/SampleModel';
#Component({
selector: 'addsample',
templateUrl: './addsample.component.html'
})
export class AddSampleComponent {
private statuses: Status[];
private users: User[];
barCode: string;
createdBy: number;
statusId: number;
constructor(private _http: Http) {
_http.get('/api/Status').subscribe(result => {
this.statuses = result.json() as Status[];
});
_http.get('/api/User').subscribe(result => {
this.users = result.json() as User[];
});
}
addSample() {
let headers = new Headers({ 'Content-Type': 'application/json' }
);
let options = new RequestOptions({ headers: headers });
this._http.post('/api/AddSample', JSON.stringify({ 'SampleId': null, 'Barcode': this.barCode, 'CreatedAt': null, 'CreatedBy': this.createdBy, 'StatusId': this.statusId }), options).subscribe(result => {
console.log(result.statusText);
console.log(result.url);
});
}
}
interface Status {
statusId: number;
statusTxt: string;
}
interface User {
userId: number;
firstName: string;
lastName: string;
}

How to Ajax call to controller with value pass?

How can i get value from ajax to mvc controller method in 'FileStreamResult' in mvc?I want to pass value from #Model[i].ToString() to controller by ajax.
Controller
public ActionResult Index()
{
IEnumerable<VmFile> model = _manager.fileName();
return View(model);
}
public ActionResult Upload(HttpPostedFileBase file)
{
try
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/File/"), fileName);
file.SaveAs(path);
_manager.UploadFile(file, path.ToString());
}
ViewBag.Message = "Upload successful";
return RedirectToAction("Index");
}
catch
{
ViewBag.Message = "Upload failed";
return RedirectToAction("Index");
}
}
public FileStreamResult GetFile(int Id)
{
string fileName = _manager.FileName(Id);
string filePath = ConfigurationManager.AppSettings["FilePath"] + fileName;
FileStream fs = new FileStream(Server.MapPath(filePath), FileMode.Open, FileAccess.Read);
return File(fs, "application/pdf");
}
FileManager
public string FileName (int id)
{
string fileName = _unitOfWork.FileRepository.Get(r => r.Id == id).Select(f => f.Name).First();
return fileName;
}
public IEnumerable<VmFile> fileName()
{
var file = _unitOfWork.FileRepository.Get();
var model = from r in file
select new VmFile
{
Id = r.Id,
Name = r.Name,
ThanaId =r.ThanaId,
RoadId = r.RoadId,
Url = r.Url,
UpLoadDate = r.UpLoadDate,
FCategoryId = r.FCategoryId,
FileType = r.FileType
};
return model;
}
public void UploadFile(HttpPostedFileBase file,string path)
{
string fName = file.FileName;
string[] typ = fName.Split('.');//Regex.Split(fName, #".");
File newFIle = new File
{
Name = fName,
Url = path,
FCategoryId = 1,
ThanaId = 23201,
RoadId = 12,
FileType = typ[1],
UpLoadDate = DateTime.Now
};
_unitOfWork.FileRepository.Insert(newFIle);
_unitOfWork.Save();
}
VmFile
public class VmFile
{
public int Id { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public Nullable<short> BridgeId { get; set; }
public Nullable<DateTime> UpLoadDate { get; set; }
public Nullable<double> FromChain { get; set; }
public Nullable<double> ToChain { get; set; }
public string FileType { get; set; }
public Nullable<int> FCategoryId { get; set; }
public Nullable<int> ThanaId { get; set; }
public Nullable<int> RoadId { get; set; }
}
View
#model IEnumerable<RSDMS.ViewModel.VmFile>
#{
Layout = null;
}
<html>
<head>
<link href="~/Content/bootstrap-theme.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="header" class="container">
<h2>Document Module</h2>
<div class="panel panel-default">
<div id="h2" class=" panel panel-primary "><h4 id="h4">Document Type</h4></div>
<div id="form" class=" panel-body">
<form role="form">
<label class="checkbox-inline">
<input type="checkbox" value="">A-Road Related
</label>
<label class="checkbox-inline">
<input type="checkbox" value="">B-Road+Structure Relate
</label>
<label class="checkbox-inline">
<input type="checkbox" value="">C-
</label>
<label class="checkbox-inline">
<input type="checkbox" value="">Option 1
</label>
<label class="checkbox-inline">
<input type="checkbox" value="">Option 2
</label>
<label class="checkbox-inline">
<input type="checkbox" value="">Option 3
</label>
</form>
</div>
</div>
<div id="listpanel" class="panel-primary">
<h1>List Panel</h1>
<div id="file">
<table>
<th>File Name</th>
#foreach (var file in Model)
{
<tr>
<td>
<li>
#file.Name
</li>
</td>
</tr>
<br />
}
</table>
</div>
#using (Html.BeginForm("Upload", "Document", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
<label class="btn btn-block btn-primary">
Browse … <input type="file" name="file" id="file" style="display: none;">
</label>
<input type="submit" class="btn" value="Upload">
}
</div>
<div id="frame" class="panel-body">
<div id="frame">
<iframe src="#Url.Action("GetFile", "Document")" width="900px" height="500px"></iframe>
</div>
</div>
</div>
</body>
</html>
<style>
#h2 {
background-color: lightblue;
height: 40px;
}
#h4 {
margin-left: 20px;
}
#header {
margin-left: 50px;
margin-right: 50px;
}
#frame {
float: right;
margin-bottom: 50px;
}
#listpanel {
float: left;
}
</style>
<script>
$(document).ready(function(e) {
// var p = { Data: $('#fileId').val() };
//var currentDataItem = this.dataItem(this);
//id = currentDataItem.Id;
alert($('#fileId').attr('id'));
var p = { Data: $('#fileId').val() };
alert(p);
var id = $('#fileId').text();
alert(id);
$('#fileId').click(function () {
$.ajax(
{
//url: '#Url.Action("GetFile", "Document")?id=' + id,
url: '/Document/GetFile',
type: "POST",
data: {Id:id},
success:function(data)
{
},
error:function(e)
{
}
});
})
});
</script>
Your javascript code should be wrapped in a jQuery load function, like this:
$(function () {
//Paste all your java script here
});
That was the only change I made on my side and the AJAX call to GetFile in the Document controller is now working
As Denis Wessels said you have to enclose jquery code inside document ready block
$( document ).ready(function() {
var currentDataItem = this.dataItem(this.select());
id = currentDataItem.Id;
var p = { Data: $('#fileId').val() };
$('#fileId').click(function () {
$.ajax(
{
url: '#Url.Action("GetFile", "Document")?id=' + id,
//url: '/Document/GetFile',
type: "POST",
// data: {Id:id},
success:function(data)
{
},
error:function(e)
{
}
});
})
});
First all let me correct certain mistakes in your code. In view haven't passed any id that could be passed in the action method. So either in the FileManager class change the returntype of GetData method as
Dictionary<int,string>
OR
create a model class say FileManagerModel as follows
public class FileManagerModel
{
public int ID {get;set;}
public string FileName{get;set;}
}
and change the return type as
List<FileManagerModel>
accordingly change the model in the view as
#model Dictionary<int, string> // If the return type is Dictionary<int,string>
and then in the view change your for loop as follows
#foreach(var file in Model)
{
<tr>
<td>
<li>
#file.Value
</li>
</td>
</tr>
<br />
}
and also change your GetFile method as follows
public FileStreamResult GetFile(int? id)
{
string fileName = "IFrameTest.txt";
var t = ConfigurationManager.AppSettings["FilePath"];
string filePath = ConfigurationManager.AppSettings["FilePath"] + fileName;
FileStream fs = new FileStream(Server.MapPath(filePath), FileMode.Open, FileAccess.Read);
return File(fs, "text/plain");
}
add nullable int arguement in your method as on page load your id will be null.
As the method by default is HTTPGET method in your Ajax call you need to make changes as follows
<script>
$(document).ready(function(e) {
var id = $('#fileId').text();
$('#fileId').click(function (event) {
event.preventDefault();
var id = $(this).data("id");
$.ajax(
{
url: '#Url.Action("GetFile", "Document")',
type: "GET",
data: { id: id },
success:function(data)
{
},
error:function(e)
{
}
});
})
});
</script>
On doing these changes it worked for me .I hope this will rectify your issue
UPDATE
If you are using IEnumerable pass the Id in the data attribute as
#file.Name

javascript function not defined error on click on a button

Imagine below MVC parent model:
Model:
Namespace MyProject.SampleModel
{
public class ViewModelExample {
public FirstModel BoolValues { get; set; }
public SecondModel NamesValues { get; set; }
}
}
Namespace MyProject.SampleModel
{
public class FirstModel
{
public bool MyBoolean1 { get; set; }
public bool MyBoolean2 { get; set; }
}
public class SecondModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
View:
#model MyProject.SampleModel.ViewModelExample
#using (Html.BeginForm("MyAction", "MyController", FormMethod.Post, htmlAttributes: new { id = "Myform" }))
{
(...)
#Html.CheckBoxFor(m => m.BoolValues.MyBoolean1)
(...)
<input id="submitButton" type="button" value="Add" onclick="InitiateSequence();" />
(...)
}
<script type="text/javascript" src="~/Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
(...)
function InitiateSequence()
{
// Do some stuff
}
(...)
function ScriptSample() {
if(#(Model.BoolValues.MyBoolean1 ? "true" : "false")
{
// It's true, do some stuff
}
else
{
// It's false, do some stuff
}
}
</script>
Controller:
public ActionResult MyAction(ViewModelExample model)
{
model.FirstModel = new TestsModel(); // I do not instantiate SecondModel as in the view for this controller i do not use it
return View(model);
}
Page is loading correctly, but when I click on the button it says javascript function InitiateSequence is not defined.... what's happening?
That could be because most possibly the function appears where it is not supposed to be. Also don't use inline attributes to bind the handlers, use event binding instead of inline handler.
<input id="submitButton" type="button" value="Add" />
and
<script type="text/javascript">
(...) //whatever code
$(function(){
$('#submitButton').on('click', InitiateSequence);
});

Categories

Resources