I'm creating asp.net mvc 5 application.In that application I want generate a Folder once I click a button on front end view page.
I want to generate that folder with in following location ~/Essential_Folder/
<input type = "button" value="Create_Folder" class="btn btn-default" id="create_folder"/>
How can I do this ,
can I do this using Server side language (in my case its C#), if its how ?
is this possible to do using client side language (such as JavaScript) ?
script
<script type="text/javascript">
$('btn-default').click(function () {
});
</script>
As #Stephen mentioned, you need to use ajax in order to create a folder. So you can have an action method like this:
[HttpPost]
public JsonResult CreateDirectory()
{
//if location has folder called "Essential_Folder" it should allow to goto inside of this if condition
if (Directory.Exists(Server.MapPath("~/Content/Essential_Folder/")))
{
Directory.CreateDirectory(Server.MapPath(string.Format("~/Content/Essential_Folder/NewDir_{0}",
DateTime.Now.Millisecond)));
return Json("OK");
}
return Json("NO");
}
And your ajax call should something like this:
<script type="text/javascript">
$('.btn').click(function() {
$.ajax({
url: "#Url.Action("CreateDirectory")",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
alert(response.responseText);
},
success: function (response) {
if (response === 'OK')
alert("Directory has been created");
else
alert("errro");
}
});
});
</script>
Related
This JS code works properly in the .cshtml file, but not working in .js file(external javascript file). Can anyone help me? i am also trying with Ajax GET but also not working in js file
[Area("Administrator")]
[Authorize(Roles = "Administrator")]
public class HomeController : Controller
{
private readonly ApplicationDbContext _context;
public HomeController(ApplicationDbContext context)
{
_context = context;
}
public JsonResult EarningChart()
{
var earning = _context.Orders.Where(o => o.Status == OrderStatus.Completed).ToList();
return Json (earning);
}
<script type="text/javascript">
$(function () {
//ajax function for fetch data
$.ajax({
type: "GET",
url: '#Url.Action("EarningChart","Home",new { area ="Administrator"})',
success: function (data) {
alert('succeed');
},
error: function () {
alert('Failed');
}
});
});
</script>
#Url.Action() is razor (server side) code and can't be used in .js file .You can add a hidden field in your main page to store url, then use javascript/jquery to get the url from the hidden field in .js file :
#Html.Hidden("MyURL", Url.Action("EarningChart","Home",,new { area ="Administrator"}))
Then in your js file :
<script type="text/javascript">
$(function () {
var myUrl = $("#MyURL").val();
//ajax function for fetch data
$.ajax({
type: "GET",
url: myUrl,
success: function (data) {
alert('succeed');
},
error: function () {
alert('Failed');
}
});
});
</script>
You don't show any js file or any cshtml file
From your comments I see you have :
<script type="text/javascript"> $(function () { //ajax function for fetch data $.ajax({ type: "GET", url: '#Url.Action("EarningChart","Home",new { area ="Administrator"})', success: function (data) { alert('succeed'); }, error: function () { alert('failed'); } }); }); </script>
I will assume your question is that if you have above code in your cshtml file it works but if you have above code in a seperate js file it doesn't work
In order to include your js file you need to include it in your cshtml page like this:
<script src="yourJsFilePathHere"></script>
I have two views (create/edit) that require the same javascript for client-side functions. I want to place my javascript into a separate file so I can reference/reuse the script on both my views but I cannot do this because I am using MVC extension methods in my javascript.
For example:
$.ajax({
type: 'GET',
url: '#Url.Action(MVC.Attribute.GetTargetedOrganisationAttributeScope())',
traditional: true,
data: { organisationIDs: ids },
success: function(data) {
// ...
}
}
});
One method I found was to place my javascript in a partial view and reference that as it allows me to use MVC extensions. Is this the correct method? Is there a better way of achieving this?
#section Scripts{
#{
Html.RenderPartial(MVC.Attribute.Views.ViewNames._js);
}
}
View
function BuscarPaciente() {
var identificacion = $("#identificacion").val();
$.ajax({
url: "#Url.Action("BuscarDatos")",
data: { identificacion: identificacion },
type: "POST",
success: function(response) {
$("#resultado").hide("slow", function() {
$(this).html(response);
$(this).show("slow");
});
}
});
};
Controller
public ActionResult BuscarDatos(string identificacion)
{
CAPBAS capbas = db.CAPBAS.SingleOrDefault(c => c.MPCedu == identificacion);
return PartialView("DatosUsuario", capbas);
}
I am working with ASP.Net Core 2.1, and trying to upload a file while returning it's url, without refreshing the page.
I am trying to write the JavaScript in site.js as the _RenderPartial("scripts") renders all scripts at the end of the page and hence directly using script tag in the razor view is not working. Secondly, adding it to site.js gives me an opportunity to call the script across the site views.
My Controller action looks like :
[HttpPost]
[DisableRequestSizeLimit]
public async Task<IActionResult> Upload()
{
// Read & copy to stream the content of MultiPart-Form
// Return the URL of the uploaded file
return Content(FileName);
}
My view looks like :
<form id="FileUploadForm" action="~/Resources/Upload" method="post" enctype="multipart/form-data">
<input name="uploadfile" type="file" />
<button name="uploadbtn" type="submit" onclick="SubmitForm(this.parentElement, event)">Upload</button>
The site.js currently looks like :
function SubmitForm(form, caller) {
caller.preventDefault();
$.ajax(
{
type: form.method,
url: form.action,
data: form.serialize(),
success: function (data) { alert(data); },
error: function (data) { alert(data); }
})}
Presently, the code bypasses the entire script and the file is uploaded and new view displaying the file name is returned. I need help to create the javascript.
Unfortunately the jQuery serialize() method will not include input file elements. So the file user selected is not going to be included in the serialized value (which is basically a string).
What you may do is, create a FormData object, append the file(s) to that. When making the
ajax call, you need to specify processData and contentType property values to false
<form id="FileUploadForm" asp-action="Upload" asp-controller="Home"
method="post" enctype="multipart/form-data">
<input id="uploadfile" type="file" />
<button name="uploadbtn" type="submit">Upload</button>
</form>
and here in the unobutrusive way to handle the form submit event where we will stop the regular behavior and do an ajax submit instead.
$(function () {
$("#FileUploadForm").submit(function (e) {
e.preventDefault();
console.log('Doing ajax submit');
var formAction = $(this).attr("action");
var fdata = new FormData();
var fileInput = $('#uploadfile')[0];
var file = fileInput.files[0];
fdata.append("file", file);
$.ajax({
type: 'post',
url: formAction,
data: fdata,
processData: false,
contentType: false
}).done(function (result) {
// do something with the result now
console.log(result);
if (result.status === "success") {
alert(result.url);
} else {
alert(result.message);
}
});
});
})
Assuming your server side method has a parameter of with name same as the one we used when we created the FormData object entry(file). Here is a sample where it will upload the image to the uploads directory inside wwwwroot.
The action method returns a JSON object with a status and url/message property and you can use that in the success/done handler of the ajax call to whatever you want to do.
public class HomeController : Controller
{
private readonly IHostingEnvironment hostingEnvironment;
public HomeController(IHostingEnvironment environment)
{
_context = context;
hostingEnvironment = environment;
}
[HttpPost]
public async Task<IActionResult> Upload(IFormFile file)
{
try
{
var uniqueFileName = GetUniqueFileName(file.FileName);
var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
var filePath = Path.Combine(uploads, uniqueFileName);
file.CopyTo(new FileStream(filePath, FileMode.Create));
var url = Url.Content("~/uploads/" + uniqueFileName);
return Json(new { status = "success", url = url });
}
catch(Exception ex)
{
// to do : log error
return Json(new { status = "error", message = ex.Message });
}
}
private string GetUniqueFileName(string fileName)
{
fileName = Path.GetFileName(fileName);
return Path.GetFileNameWithoutExtension(fileName)
+ "_"
+ Guid.NewGuid().ToString().Substring(0, 4)
+ Path.GetExtension(fileName);
}
}
Sharing the code that worked for me, implementing #Shyju's answer.
View ( Razor Page ):
<form name="UploadForm" action="~/Resources/Upload" method="post" enctype="multipart/form-data">
<input name="uploadfile" type="file" />
<button name="uploadbtn" type="submit" onclick="SubmitForm(this.parentElement, event)">Upload</button>
AJAX code added in Site.js (to make it a reusable):
// The function takes Form and the event object as parameter
function SubmitForm(frm, caller) {
caller.preventDefault();
var fdata = new FormData();
var file = $(frm).find('input:file[name="uploadfile"]')[0].files[0];
fdata.append("file", file);
$.ajax(
{
type: frm.method,
url: frm.action,
data: fdata,
processData: false,
contentType: false,
success: function (data) {
alert(data);
},
error: function (data) {
alert(data);
}
})
};
if you want to submit the form without using ajax request
var form = document.getElementById('formId');
form.submit();
I want to call action from view using JavaScript, but I can't do this:
Here is my code:
#if (ViewBag.Status == true)
{
<script language="javascript" type="text/javascript">
if (confirm("Some message"));
//And here i want to add action call
</script>
}
I'm trying to use #Html.Action, but this ruined script code and confirm message didn't show.
When I write it as shown here: Calling ASP.NET MVC Action Methods from JavaScript:
#if (ViewBag.Status == true)
{
<script language="javascript" type="text/javascript">
if (confirm("Some message"));
{
$.ajax({
url: 'MyController/MyAction',
data: { id: id },
success: function () {
alert('Added');
}
});
}
</script>
}
nothing changed. It displays confirmation dialog but don't calling method
You need to change your code to something like this.In which case you would call: func(#ViewBag.Status)
#Section scripts
<script language="javascript" type="text/javascript">
//val in this case being the value of the ViewBag passed from where the call is occurring
function func(val) {
if (val == true) {
if (confirm("Some message"));
{
$.ajax({
url: 'MyController/MyAction',
data: { id: id },
type: "POST",
success: function () {
alert('Added');
}
});
}
}
}
</script>
end section
Also in the controller remember to apply the [HttpPost] attribute on the method like so:
[HttpPost]
public ActionResult MyAction(string id)
{
// your code
return Json();//your response
}
If i understood you correctly, you want to call your Action method in controller from javascript. And show confirm message on success.
Here is the code for that:
if ('#ViewBag.Status' == true)
{
$.ajax({
type: "Post",
url: '#Url.Action("MyAction", "MyController")',
data: { Id: Id },
dataType: "json",
traditional: true,
success: function (data) {
alert("Success");
},
});
}
To hit the success, you need to return the JsonResult or ContentResult or ActionResult from controller.
JavaScript cannot call a controller action unless you use Ajax or another client side mechanism to talk to the server!
What you need it to use xhr to tak to the server or use following jQuery code
<script src='jquery-latest.js'></script>
#if (ViewBag.Status == true)
{
<script language="javascript" type="text/javascript">
if (confirm("Some message")){
//And here i want to add action call
$.get('#Url("action","controller",null)')
.done(function(data){
//use loaded data here
}).fail(function(e,f,g){
console.log({e:e,f:f,g:g})
});
}
</script>
}
PS: don't forget to reference the jQuery library
Senario :
I wanna call a Helper method from JavaScript.I produced some controls in server side such as Grid,DataTimePicker,SlideShow, ... for ASP.NET MVC.
Now, how do I invoke helper method from JavaScript ?
I found the way for invoke helper method in view(ASP.NET MVC) .
for example:
namespace Component
{
public class HelperMethod
{
public static MvcHtmlString GridSort(this HtmlHelper helper,string fieldName)
{
//do something
}
}
}
Code in my view:
#using Component
<script>
$(document).ready(function(){
var message='FirstName';
var result = "#Html.GridSort(message)"; // here is the Error
$("div#grdUsers").html(result );
});
</script>
<div id="grdUsers">
//grid elements
</div>
Now, the problem is : I can't pass JavaScript Variable(message) value to helper method(GridSort).
What can I do ?
1st Way:- make it an ACTION returning json - and call with Ajax.
#using Component
<script>
$(document).ready(function(){
var message='FirstName';
$.ajax({
url: '/Your Controller name /your Method name',
type: 'POST',
data: {message:message},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function () {
},
error: function (error) {
alert('error');
}
});
});
</script>
<div id="grdUsers">
//grid elements
</div>
2nd Way:-use Request.QueryString["message"]