I am adding a comments part in my project, I would like to use real-time using signalR.
I'm using Ajax for adding comments, and I want to refresh data for all users after the comment inserts into the database.
This is my code in Razor view :
<form asp-action="SendComment" asp-controller="Home" asp-route-subId="#Model.Subject.Id"
asp-route-AccountName="#User.Identity.Name" onsubmit="return jQueryAjaxPost(this);">
<textarea name="comment" id="myTextbox" required class="form-control mb-3" rows="3" cols="1" placeholder="اكتب هنا"></textarea>
<div class="d-flex align-items-center">
<button type="submit" id="myBtn" class="btn bg-blue-400 btn-labeled btn-labeled-right ml-auto"><b><i class="icon-paperplane"></i></b> ارسال</button>
</div>
</form>
Ajax code :
jQueryAjaxPost = form => {
try {
$.ajax({
type: 'POST',
url: form.action,
data: new FormData(form),
contentType: false,
processData: false,
success: function (res) {
if (res.isValid) {
$('#view-all').html(res.html)
}
else
$('#form-modal .modal-body').html(res.html);
},
error: function (err) {
console.log(err)
}
})
//to prevent default form submit event
return false;
} catch (ex) {
console.log(ex)
}
}
signalR code (Not finished)
<reference path="../lib/signalr/browser/signalr.js" />
$(() => {
let connection = new signalR.HubConnectionBuilder().withUrl("/signalServer").build();
connection.start();
connection.on("refreshData", function () {
loadData();
});
loadData();
function loadData() {
debugger;
$.ajax({
type: 'GET',
url: '#Url.Action("refreshComments","Home")',
success: function (res) {
$('#view-all').html(res);
}
})
}
});
Code-behind :
var newComment = new CourseComment
{
Comment = comment,
Date = DateTime.Now,
ApplicationUser = user,
SubjectId = subId,
CreatedDate = DateTime.Now
};
_courseCommnt.Entity.Insert(newComment);
await _courseCommnt.SaveAsync();
await _signalR.Clients.All.SendAsync("refreshData");
_toastNotification.AddSuccessToastMessage("تم ارسال التعليق بنجاح");
var courseComments = await _courseCommnt.Entity.GetAll().Include(a => a.ApplicationUser)
.Where(a => a.SubjectId == subId).OrderByDescending(a => a.Date).AsNoTracking().ToListAsync();
var vm = new HomeViewModel
{
CourseComments = courseComments
};
return Json(new
{
isValid = true,
html = Helper.RenderRazorViewToString(this, "_SubjectComments", vm)
});
Related
Here's code for Controller :
public function Update()
{
$id_form = $this->input->post('id_form');
$no_request = $this->input->post('no_request');
$data = {
"no_request" => $no_request,
"date_ps" => date('d M Y')
}
return $this->db->where('id_form', $id_form);
return $this->db->update('table', $data);
}
Here's code for View :
<input type="hidden" name="id_form" id="id_form"></br>
<input type="text" name"no_request" id="no_request"></br>
Edit
Here's code for Ajax :
$('#btn_update').on('click', function() {
var id_form = $('#id_form').val();
var no_request = $('#no_request').val();
var date_ps = $(date_ps).val();
$.ajax({
type: "POST",
url: "<?= site_url('Controller/Update') ?>",
dataType: "JSON",
data: {
id_form: id_form,
no_request: no_request,
date_ps: date_ps
},
success: function(data) {
console.log(date_ps);
}
})
}
But The result for date_ps is undefined, How can I get the date_ps value without having to undefined
I'm dynamically adding data to the database using AJAX and displaying them using foreach loop in MVC, I have also added a button to remove the those data using ajax call.
HTML/MVC code:
<div id="divaddrules" class="form-group row">
#try
{
foreach (var item in ViewBag.AdditionalRules)
{
<div class="col-sm-10">
<p style="font-size:large">#item.AdditionalDesc</p>
</div>
<div class="col-sm-2">
<input type="button" onclick="Removeinput(#item.id)" class="text-dark" style="border:none; background-color:transparent" value="X" />
</div>
}
}
catch (Exception ex){ }
</div>
Now when I click on Remove button it call the following JS code:
function Removeinput(id) {
var datas = {};
datas.addId = id
$.ajax({
url: "/Rooms/RemoveAdditionalRules",
type: "GET",
data: datas,
success: function (result) {
alert(result.id);
$("#divaddrules").load(window.location.href + " #divaddrules");
},
error: function (result) {
alert("Error: " + result.status);
}
});
}
and its passing to this controller:
[HttpGet]
[Authorize]
public ActionResult RemoveAdditionalRules(int addId)
{
HouseRules rules = db.HouseRules.Find(addId);
db.HouseRules.Remove(rules);
db.SaveChanges();
return Json(JsonRequestBehavior.AllowGet);
}
I'm getting 500 error on ajax call error.
Can anyone tell me where I'm doing it wrong? Please.. I'm stuck here.
Update:
Attached screenshot: Debug Screenshot
Write your Removeinput function as follows:
function Removeinput(id) {
$.ajax({
url: "/Rooms/RemoveAdditionalRules",
type: "GET",
data: { addId : id},
success: function (response) {
alert(response);
$("#divaddrules").load(window.location.href + " #divaddrules");
},
error: function (result) {
alert("Error: " + result.status);
}
});
}
Then in the controller method:
[HttpGet]
[Authorize]
public ActionResult RemoveAdditionalRules(int addId)
{
AdditionalRules rules = db.AdditionalRules.Find(addId); // Here was the problem. He was pointing to the wrong table that has fixed over team viewer.
db.AdditionalRules.Remove(rules);
db.SaveChanges();
return Json(addId,JsonRequestBehavior.AllowGet);
}
the problem it is missing values on db, in the image you ask to id 25 but return null and you try to remove a item passing null value.
so in your case you need to validate before remove or fix the missing data:
[HttpGet]
[Authorize]
public ActionResult RemoveAdditionalRules(int addId)
{
HouseRules rules = db.HouseRules.Find(addId);
If(rules == null)
{
//return error msg.
return Json(JsonRequestBehavior.AllowGet);
}
db.HouseRules.Remove(rules);
db.SaveChanges();
return Json(JsonRequestBehavior.AllowGet);
}
make your input type submit, may this was helpful
function deleterelation(id) {
debugger;
if (id > 0)
$.ajax({
url: "/Relations/Delete/" + id,
type: "get",
datatype: "json",
data: { id: id },
success: function (response) {
debugger;
if (response != null) {
$("#txtDName").text(response.name);
$("#DRelationId").val(response.id);
$("#DeleteRelation").modal("show");
}
},
error: function (response) {
$("#DeleteRelationLoading").hide();
$("#DeleteRelation_btn_cancel").show();
$("#DeleteRelation_btn_save").show();
}
});
else
toastr.error("Something went wrong");
}
<input type="submit" onclick="Removeinput(#item.id)" class="text-dark" style="border:none; background-color:transparent" value="X" />
if this not work plz let me know
I'm using Angular 2 with Spring MVC. I currently have an Upload component that makes an AJAX call to the Spring backend and returns a response of parsed data from a .csv file.
export class UploadComponent {
uploadFile: function(){
var resp = this;
var data = $('input[type="file"]')[0].files[0];
this.fileupl = data;
var fd = new FormData();
fd.append("file", data);
$.ajax({
url: "uploadFile",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(response) {
resp.response = response;
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage);
}
});
};
}
This works, I get a valid response back; however, is there a more angular 2 way to pass this file to Spring and receive a response? I've been looking into creating an injectible service and using subscribe, but I've been struggling to get a response back
I ended up doing the following:
import { Component, Injectable } from '#angular/core';
import { Observable} from 'rxjs/Rx';
const URL = 'myuploadURL';
#Component({
selector: 'upload',
templateUrl: 'upload.component.html',
styleUrls: ['upload.component.css']
})
export class UploadComponent {
filetoUpload: Array<File>;
response: {};
constructor() {
this.filetoUpload = [];
}
upload() {
this.makeFileRequest(URL, [], this.filetoUpload).then((result) => {
this.response = result;
}, (error) => {
console.error(error);
});
}
fileChangeEvent(fileInput: any){
this.filetoUpload = <Array<File>> fileInput.target.files;
}
makeFileRequest(url: string, params: Array<string>, files: Array<File>) {
return new Promise((resolve, reject) => {
let formData: any = new FormData();
let xhr = new XMLHttpRequest();
for(let i =0; i < files.length; i++) {
formData.append("file", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
};
xhr.open("POST", url, true);
xhr.send(formData);
});
}
}
I can then inject a response into my html like:
<div class="input-group">
<input type="file" id="file" name="file" placeholder="select file" (change)="fileChangeEvent($event)">
<input type="submit" value="upload" (click)="upload()" class="btn btn-primary">
</div>
<div *ngIf="response">
<div class="alert alert-success" role="alert">
<strong>{{response.myResponseObjectProperty | number}}</strong> returned successfully!
</div>
This has support for multiple file uploads. I created it as an injectable service in this plunkr:
https://plnkr.co/edit/wkydlC0dhDXxDuzyiDO3
I have the ability to upload a file and save it to a directory. That is all good. I need to make an entry to my database with information about that file. So far I am not sure how to pass a value from the view to the controller in this particular case. I have tried to pass it as a method parameter but the value is not getting posted.
Here is my Razor form:
#using (Html.BeginForm("AjaxUpload", "Cases", FormMethod.Post, new { enctype = "multipart/form-data", id = "ajaxUploadForm" }))
{
<fieldset>
<legend>Upload a file</legend>
<label>File to Upload: <input type="file" name="file" />(100MB max size)</label>
<input id="ajaxUploadButton" type="submit" value="Submit" />
</fieldset>
}
<div id="attachments">
#Html.Partial("_AttachmentList", Model.Attachments)
</div>
Here is my jQuery to ajaxify the form:
$(function () {
$('#ajaxUploadForm').ajaxForm({
iframe: true,
dataType: "json",
beforeSubmit: function () {
$('#ajaxUploadForm').block({ message: '<h1><img src="/Content/images/busy.gif" /> Uploading file...</h1>' });
},
success: function (result) {
$('#ajaxUploadForm').unblock();
$('#ajaxUploadForm').resetForm();
$.growlUI(null, result.message);
//$('#attachments').html(result);
},
error: function (xhr, textStatus, errorThrown) {
$('#ajaxUploadForm').unblock();
$('#ajaxUploadForm').resetForm();
$.growlUI(null, 'Error uploading file');
}
});
});
Here is the controller method:
public FileUpload AjaxUpload(HttpPostedFileBase file, int cid)
{
file.SaveAs(Server.MapPath("~/Uploads/" + file.FileName));
var attach = new Attachment { CasesID = cid, FileName = file.FileName, FileType = file.ContentType, FilePath = "Demo", AttachmentDate = DateTime.Now, Description = "test" };
db.Attachments.Add(attach);
db.SaveChanges();
//TODO change this to return a partial view
return new FileUpload { Data = new { message = string.Format("{0} uploaded successfully.", System.IO.Path.GetFileName(file.FileName)) } };
}
I would like cid to be passed to this method so that I can insert a record into the database.
You could include it as a hidden field inside the form:
#Html.Hidden("cid", "123")
or as a route value:
#using (Html.BeginForm(
"AjaxUpload",
"Cases",
new { cid = 123 },
FormMethod.Post,
new { enctype = "multipart/form-data", id = "ajaxUploadForm" }
))
{
...
}
What i want to do:
at page load to automatically pop up a jquery dialog fill in some data, post that to an action and close the dialog (regardless if the action succeeds or not).
in the View in which the pop up should occur i have the following:
<script type="text/javascript">
$(function () {
$('#PopUpDialog').dialog(
{
modal: true,
open: function ()
{
$(this).load('#Url.Action("Subscription", "PopUp")');
},
closeOnEscape: false
}
);
$('.ui-dialog-titlebar').hide();
$('#closeId').live('click',function () {
$('#PopUpDialog').dialog('close');
return false;
}
);
$('#SubscriptionForm').submit(function () {
$("#PopUpDialog").dialog("close");
$.ajax({
url: encodeURI('#Url.Action("Subscription", "PopUp")' ),
type: this.method,
data: $(this).serialize()
})
return fase;
}
);
});
</script>
the Subscription view has the following:
#using (Html.BeginForm( new { id = "SubscriptionForm" }))
{
#Html.ActionLink(Deals.Views.PopUp.SubscriptionResources.AlreadySubscribed, "", null, new { id = "closeId" })
<br />
<br />
#Deals.Views.PopUp.SubscriptionResources.FillEmail
#Html.TextBoxFor(m => Model.Email)
<input type="submit" id="subscribeId" value="#Deals.Views.PopUp.SubscriptionResources.IWantToSubscribe" />
<br />
}
which works fine.
The POST action is defined as follows:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult Subscription(FormCollection formValues)
//public void Subscription(FormCollection formValues)
{
Deals.ViewModels.PopUpSubscriptionVM VM = new ViewModels.PopUpSubscriptionVM();
TryUpdateModel(VM);
if (!String.IsNullOrEmpty(VM.Email))
{
//do the update to the dbms
}
return Json(new { success = true });
}
The problem is that after posting back i get an empty screen with the success message, which i don't want!
What am i doing wrong?
You can handle the success and error callbacks:
$('#SubscriptionForm').submit(function () {
$("#PopUpDialog").dialog("close");
$.ajax({
url: encodeURI('#Url.Action("Subscription", "PopUp")' ),
type: this.method,
data: $(this).serialize(),
success: function (result) {
//Do Whatever you want to do here
},
error: function (x, e) {
//Do Whatever you want to do here
}
})
return fase;
}
To see what i am doing wrong i set up a small project (ASP.NET MVC 3) with the following ingredients:
<script type="text/javascript">
$(function () {
// Does not cache the ajax requests to the controller e.g. IE7/9 is doing that...
$.ajaxSetup({ cache: false });
var $loading = $('<img src="#Url.Content("~/images/ajax-Loader.gif")" alt="loading" class="ui-loading-icon">');
var $url = '#Url.Action("Subscription", "PopUp")';
var $title = 'Some title';
var $dialog = $('<div></div>');
$dialog.empty();
$dialog
.append($loading)
.load($url)
.dialog({
autoOpen: false
, closeOnEscape: false
, title: $title
, width: 500
, modal: true
, minHeight: 200
, show: 'fade'
, hide: 'fade'
});
$dialog.dialog("option", "buttons", {
"Cancel": function () {
$(this).dialog("close");
$(this).empty();
},
"Submit": function () {
var dlg = $(this);
$.ajax({
url: $url,
type: 'POST',
data: $("#SubscriptionForm").serialize(),
success: function (response) {
//$(target).html(response);
dlg.dialog('close');
dlg.empty();
});
}
});
$dialog.dialog('open');
})
</script>
The controllers' actions:
public ActionResult Subscription()
{
Thread.Sleep(2000); //just for testing
TestModalAjax.ViewModels.PopUpVM VM = new ViewModels.PopUpVM();
return View(VM);
}
//POST
[AcceptVerbs(HttpVerbs.Post)]
//[OutputCache(CacheProfile = "ZeroCacheProfile")]
public ActionResult Subscription(FormCollection formValues)
{
TestModalAjax.ViewModels.PopUpVM VM = new ViewModels.PopUpVM();
TryUpdateModel(VM);
return Json(new { success = true });
}
...and the according View:
#model TestModalAjax.ViewModels.PopUpVM
#{
Layout = null;
ViewBag.Title = "Subscription";
}
<h2>Subscription</h2>
#* ----- NOTICE THE FOLLOWING!!! WITHOUT THIS DATA GETS NOT POSTED BACK!!!! ---- *#
#using (Html.BeginForm("Subscription","PopUp",FormMethod.Post, new { id="SubscriptionForm"}))
{
<h1> Give me your name</h1>
#Html.TextBoxFor(M => Model.Name)
}
...so it seems everything works as expected!