I want to use the ()Load method. I have done it without a problem on PHP but now I want to do the same on ASP.net.
<script>
$(document).ready(function () {
$("#btn").click(function () {
$("#test").load("footershop.txt")
});
});
</script>
<section class="shop">
<footer>
<img src="#Url.Content("~/Images/klader.jpg")" alt="klader">
<div id="test" >
<p class="shoptext">text</p>
</div><br />
<button id="btn">Mejla oss</button>
</footer>
</section>
Here is my code in ASP.net. I put the "footershop.txt" in the App_Data folder. It does not show up. Where should I put the textfile in ASP?
you can use $.ajax instead of load to show the textfile content in the div. The txt file should be in the same directory path for the below code to work else you have to specify the actual path at the url property
<script>
$(document).ready(function () {
$("#btn").click(function () {
$.ajax({
url : "footershop.txt",
dataType: "text",
success : function (data) {
$("#test").html(data);
}
});
});
});
</script>
you should be testing it from a server not from local system as there might access issues in local to read the txt file.
Related
I am using DropZone on a RAZOR page in ASP.NET core 2.0 with other form inputs like this -
DzDemo.cshtml Page -
<form method="post" enctype="multipart/form-data">
<input type="text" id="Username" name="Username" />
<div class="dropzone" id="my-dropzone" name="mainFileUploader">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</div>
</form>
<div>
<button type="submit" id="submit-all"> upload </button>
</div>
JS:-
Dropzone.options.myDropzone = {
url: "/DzDemo?handler=Upload",
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
acceptedFiles: "image/*",
// paramName: myParamName,
init: function () {
var submitButton = document.querySelector("#submit-all");
var wrapperThis = this;
submitButton.addEventListener("click", function () {
wrapperThis.processQueue();
});
this.on('sendingmultiple', function (data, xhr, formData) {
formData.append("UserName", $("#Username").val());
});
this.on('error',
function (file, response) {
console.log(response);
alert(response);
});
}
};
DzDemo.cshtml.cs Page:-
[HttpPost]
public IActionResult OnPostUpload()
{
var data = Request.Form; //This is
return Page();
}
but I get 400 response from server and I am not able to process uploaded file server side Also it wont hot the Upload method on server side. Please help
One thing that will result in 400 using dropzone.js together with Razor Pages is if the AntiforgeryToken is missing from the form.
This is normally injected automatically but removing _viewimports or its taghelpers will prevent this.
To verify just add this line inside the <form/> element or look at the debug console for error messages.
#Html.AntiForgeryToken()
I got it working by setting the headers options
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() }
Certainly, you need to have either at <form /> element or explicitly adding the #Html.AntiForgeryToken() in your page
Add this line in sendingmultiple, it will resolve your pb:
this.on('sendingmultiple', function (data, xhr, formData) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
});
I'm using summernote editor, and I want to retrieve its content in code behind.
I tried to use the following ways , but it returns empty(null)
1-
default.aspx
<div class="summernote" id="txtTest" runat="server"></div>
Code behind:
string content= txtTest.InnerText;
2-
default.aspx
<div class="summernote" id="txtTest" ></div>
Code behind:
string name = Request.Form["txtTest"];
Any suggestions?
Here is My code Working Perfectly
<div class="form-group">
<asp:Label ID="lblSummernote" runat="server" Text="Image" AssociatedControlID="txtSummernote" CssClass="control-label col-md-3"></asp:Label>
<div class="col-md-8">
<asp:TextBox ID="txtSummernote" runat="server" TextMode="MultiLine" Rows="2"></asp:TextBox>
<asp:Label ID="lblSum" runat="server" Text="Summernote"></asp:Label>
</div>
</div>
JavaScript
<script src="/Content/SummerNote/summernote.js"></script>
<script>
$(function () {
// Set up your summernote instance
$("#<%= txtSummernote.ClientID %>").summernote();
focus: true
// When the summernote instance loses focus, update the content of your <textarea>
$("#<%= txtSummernote.ClientID %>").on('summernote.blur', function () {
$('#<%= txtSummernote.ClientID %>').html($('#<%= txtSummernote.ClientID %>').summernote('code'));
});
});
</script>
<script type="text/javascript">
function funcMyHtml() {
debugger;
document.getElementById("#<%= txtSummernote.ClientID %>").value = $('#<%= txtSummernote.ClientID %>').summernote('code');
}
</script>
C# Code behind
protected void btnSubmit_Click(object sender, EventArgs e)
{
lblSum.Text = txtSummernote.Text;
}
Have you considered using a <textarea> to handle this as opposed to a <div>? Usually they are a bit easier to use with respect to storing values (as they are designed to do so) :
<textarea id="txtTest" runat="server"></textarea>
One of the ways that you might handle this would be to register an event using Summernote's available API to set the HTML content for your <textarea> element whenever focus was lost (e.g. the onblur) :
<script>
$(function () {
// Set up your summernote instance
$("#txtTest").summernote();
// When the summernote instance loses focus, update the content of your <textarea>
$("#txtTest").on('summernote.blur', function () {
$('#txtTest').html($('#txtTest').summernote('code'));
});
});
</script>
Since you are likely going to be storing HTML content within the element, you'll likely want to ensure that .NET doesn't think you are trying to exploit it. You can do this by either explicitly setting this page to ignore that process by updating the ValidateRequest property of your page :
<%# Page ... ValidateRequest = "false" %>
Or you could try simply escaping the content that is being set :
$('#txtTest').html(escape($('#txtTest').summernote('code')));
Here is how I got it working.
ref it as a class
class="summernote"
$(document).ready(function () {
$('.summernote').summernote();
});
I have a MVC 4 project where I want to call a controller from view A and than append the returned view B in view A.
something like that:
view A (aspx):
<script type="text/javascript">
function HeadBtn_Click() {
/////
var url = 'IVR/';
window.location.href = url;
////this works, but I want to stay in view A
//// example of what I want:
divContant.innerHTML = ////The returned view here////
}
</script>
<body>
<input type="image" onclick="HeadBtn_Click();" src="../../Images/buttonHodaot.png">
<div id="divContant"> ////Append Here//// </div>
</body>
view B(aspx):
////I will have alot more to append, but just for now:
<div>
<p>To Append</p>
</div>
thanks
Another approach (if you really want to render the view B after view A loads)..
Make use of AJAX and get the response HTML of view B, then append it to divContent div. Like this,
<script type="text/javascript">
function HeadBtn_Click() {
$.ajax({
type: 'GET',
url: url,
dataType: 'HTML',
success: function(data) {
$('#divContant').html(data);
}
});
}
</script>
Hope it helps, thanks.
You can use RenderAction and return viewB as partial view
<div id="divContant">
#{Html.RenderAction("controllerName","actionName");}
</div>
http://www.dotnet-tricks.com/Tutorial/mvc/Q8V2130113-RenderPartial-vs-RenderAction-vs-Partial-vs-Action-in-MVC-Razor.html
I need to get javascript values on code behind in c#.I know i can use hidden field but there is no server control on page for postback.Please tell me how can get vales in code behind.
Here is my code:
<html>
<head>
<title>Facebook Get Logged in User Details UserName,Email,Profile Image</title>
<script src="jquery-1.6.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
// Load the SDK Asynchronously
(function (d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
} (document));
// Init the SDK upon load
window.fbAsyncInit = function () {
FB.init({
appId: 'APPID', // App ID
channelUrl: '//' + window.location.hostname + '/channel', // Path to your Channel File
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function (response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
var uid = "http://graph.facebook.com/" + response.authResponse.userID + "/picture";
FB.api('/me', function (me) {
document.getElementById('auth-displayname').innerHTML = me.name;
document.getElementById('myJSString').value = me.name;
alert(document.getElementById('myJSString').value);
document.getElementById('Email').innerHTML = me.email;
document.getElementById('profileImg').src = uid;
// document.getElementById('ctl00_CPHDefault_tcTPS_TPProd_ctl01_tcProduction_TPNewTitlesStatus_ChangedRowsIndicesHiddenField').value = uid;
// alert('yyy');
})
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
} else {
// user has not auth'd your app, or is not logged into Facebook
document.getElementById('auth-loggedout').style.display = 'block';
document.getElementById('auth-loggedin').style.display = 'none';
}
});
$("#auth-logoutlink").click(function () { FB.logout(function () { window.location.reload(); }); });
}
</script>
<h1>
Facebook Login Authentication Example</h1>
<div id="auth-status">
<div id="auth-loggedout">
<div id="Result" class="fb-login-button" autologoutlink="true" scope="email,user_checkins">Login</div>
</div>
<div id="auth-loggedin" style="display: none">
Name: <b><span id="auth-displayname"></span></b>(logout)<br />
Email: <b><span id="Email"></span></b><br />
Profile Image: <img id="profileImg" />
<form runat="server">
<asp:HiddenField runat="server" id="myJSString" />
</form>
</div>
</div>
</body>
</html>
You can see there is no server control so how i can get NAME,UID variables in code behind.
Thanks
You can use a hiddenfield server control assign the values you need to it in javascript and assess it on server side. If you do not want post back then you can use jQuery ajax to send values.
Html
<asp:hiddenfield id="ValueHiddenField" runat="server"/>
Javascript
document.getElementById('ValueHiddenField').value = "yourValue";
Code behind
string yourValue = ValueHiddenField.Value;
Using jQuery ajax and web method to send values to code behind, you can find nice tutorial over here.
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: {'yourParam': '123'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Code behind
[WebMethod]
public static void YourMethod(string yourParam)
{
//your code goes here
}
I would investigate the use of ASP.NET AJAX Page Methods, because they allow for script callable stand-alone web services that live in an .aspx page, like this:
Page Method in your code-behind file (call it default.aspx for discussion's sake):
[WebMethod]
public static string SaveData(string name, string uid)
{
// Logic here to do what you want with name and uid values (i.e. save to database, call another service, etc.)
}
jQuery call to default.aspx's SaveData method:
$.ajax({
type: "POST",
url: "default.aspx/SaveData",
data: "{'name':'John', 'uid':'ABC123'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Notes: ASP.NET AJAX Page Methods automatically encode their response to JSON so you will not see any JSON serialization in the code-behind or any serialization logic at all.
For more information about ASP.NET AJAX Page Methods check out Using jQuery to directly call ASP.NET AJAX page methods
You can use following method:
<script language="javascript" type="text/javascript">
function returnString() {
var val = 'sampleValue';
return val;
}
</script>
C# Code to get the return value of the above function:
ClientScript.RegisterClientScriptBlock(this.GetType(), "alertScript", "<script language="javascript">var a=returnString();alert(a);</script>");
Or simply as Adil said, can use hidden field and assign value:
<asp:HiddenField ID="hField" Value="0" runat="server" />
<asp:Button ID="Button1" runat="server" OnClientClick="returnString();"
Text="Button" onclick="Button1_Click" />
script for assigning value:
<script language="javascript" type="text/javascript">
function returnString() {
debugger;
document.getElementById("hField").value = "sampleValue";
}
</script>
I cant' seem to work uploadify on ASP.NET MVC3, I searched a lot and the code below seem to work fine, but not for me. When I try and upload it via html uploading method it works, not so much with uploadify. All libraries are included correctly.
<!-- Not working, HTTP ERROR 500 -->
<input id="file" type="file" name="file" />
<script type="text/javascript">
$(document).ready(function () {
$('#file_upload').uploadify({
// I tried to remove "/" at the start, does not help
'uploader': '/Scripts/u/uploadify.swf',
'script': '/home/upload',
'cancelImg': '/Scripts/u/cancel.png',
'folder': '/upload',
'auto': true,
'onError': function (event, ID, fileObj, errorObj) {
alert(errorObj.type + ' Error: ' + errorObj.info);
}
});
});
</script>
<!-- Working fine -->
<form action="home/upload" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" />
</form>
Home Controller Action
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
var fileName = Path.GetFileName(file.FileName); // Object reference not set to an instance of an object. I get this if I try to upload via uploadify
file.SaveAs(Server.MapPath("~/upload/") + fileName);
return Content(fileName);
}
Didn't you debug your code? Didn't you notice that the file action argument is always null when the Upload action is hit? Your action argument is called file, so you need to specify that using the fileDataName option:
'fileDataName' : 'file',
By default uploadify uses Filedata, so if you don't want to specify this name you could also adapt your action argument name to match this:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase fileData)
{
var fileName = Path.GetFileName(fileData.FileName);
fileData.SaveAs(Path.Combine(Server.MapPath("~/upload/"), fileName));
return Content(fileName);
}
Also make sure that the ~/upload folder exists on your server. It doesn't when you create a new ASP.NET MVC application.
Another problem that I would like to point out with your code is that you have hardcoded absolutely all urls in your javascript. That's very bad and chances are that your application won't work when you deploy it in a virtual directory, say for example IIS.
In ASP.NET MVC you should always use url helpers when dealing with urls, just like that:
<script src="#Url.Content("~/Scripts/u/jquery.uploadify.v2.1.4.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/u/swfobject.js")" type="text/javascript"></script>
<input id="file_upload" type="file" name="file" />
<script type="text/javascript">
$(document).ready(function () {
$('#file_upload').uploadify({
'uploader': '#Url.Content("~/Scripts/u/uploadify.swf")',
'script': '#Url.Action("upload", "home")',
'cancelImg': '#Url.Content("~/Scripts/u/cancel.png")',
'folder': '#Url.Content("~/upload")',
'auto': true,
'onError': function (event, ID, fileObj, errorObj) {
alert(errorObj.type + ' Error: ' + errorObj.info);
}
});
});
</script>
Is use
HttpPostedFileBase file = Request.Files[0];
in my controller with Uploadify