I'm not well versed in this framework so I need some help here. In a view I want to add a link or a button on clicking which a certain file gets deleted from the server.
I've added this method to the controller:
[Authorize]
public ActionResult DeleteFile(string path)
{
if ((System.IO.File.Exists(path)))
{
try
{
System.IO.File.Delete(path);
}catch(Exception ex)
{
Debug.WriteLine("Deletion of file failed: " + ex.Message);
}
}
return View();
}
Seemed straightforward, though I'm not sure about the return View();. Now in the view, I need a form, because the path to the file that should be deleted needs to be posted to the controller, is that correct? This is what I got so far, mimicked from other code in the project:
#Html.BeginForm("DeleteFile", "Home", FormMethod.Post, new { id = "delete-attachment-form" })
{
#Html.Hidden("path", path)
}
path is a JavaScript variable containing the server path to the file that needs to be deleted. If I'm on the right track here, how do I add a button or a link to click on that will send the form?
Should just be able to add a submit button:
<input type="submit" name="submit" />
You should have a form and a button like this
#Html.BeginForm("Controller", "DeleteFile", new {Path= filePath},FormMethod.Post)
{
//Button
}
Or using Ajax and Jquery
var values = $(this).serialize();
$.ajax({
type: 'POST',
url: "url?path="+path.tostring(),
data: values ,
success: function(response) { //update view }
});
Inside your form you can add a button and then handle the button click in JavaScript.
#Html.BeginForm("DeleteFile", "Home", FormMethod.Post, new { id = "delete-attachment-form" })
{
#Html.Hidden("path", path)
<button id="delete-btn" type="button" class="btn btn-danger">
Delete
</button>
}
Then the <script type="text/javascript"> block:
$(function () {
$('#delete-btn').click(function () {
var query = $('#delete-attachment-form');
var form = query[0];
var toPost = query.serialize();
$.ajax({
url: form.action,
type: form.method,
data: toPost,
success: function (result) {
// display result
},
error: function () {
// handle error
}
})
});
});
Also, this is a good tutorial on deleting in ASP.NET MVC
Related
I have sample code like this:
<div class="cart">
<a onclick="addToCart('#Model.productId');" class="button"><span>Add to Cart</span></a>
</div>
<div class="wishlist">
<a onclick="addToWishList('#Model.productId');">Add to Wish List</a>
</div>
<div class="compare">
<a onclick="addToCompare('#Model.productId');">Add to Compare</a>
</div>
How can I write JavaScript code to call the controller action method?
Use jQuery ajax:
function AddToCart(id)
{
$.ajax({
url: 'urlToController',
data: { id: id }
}).done(function() {
alert('Added');
});
}
http://api.jquery.com/jQuery.ajax/
Simply call your Action Method by using Javascript as shown below:
var id = model.Id; //if you want to pass an Id parameter
window.location.href = '#Url.Action("Action", "Controller")/' + id;
You are calling the addToCart method and passing the product id. Now you may use jQuery ajax to pass that data to your server side action method.d
jQuery post is the short version of jQuery ajax.
function addToCart(id)
{
$.post('#Url.Action("Add","Cart")',{id:id } function(data) {
//do whatever with the result.
});
}
If you want more options like success callbacks and error handling, use jQuery ajax,
function addToCart(id)
{
$.ajax({
url: '#Url.Action("Add","Cart")',
data: { id: id },
success: function(data){
//call is successfully completed and we got result in data
},
error:function (xhr, ajaxOptions, thrownError){
//some errror, some show err msg to user and log the error
alert(xhr.responseText);
}
});
}
When making ajax calls, I strongly recommend using the Html helper method such as Url.Action to generate the path to your action methods.
This will work if your code is in a razor view because Url.Action will be executed by razor at server side and that c# expression will be replaced with the correct relative path. But if you are using your jQuery code in your external js file, You may consider the approach mentioned in this answer.
If you do not need much customization and seek for simpleness, you can do it with built-in way - AjaxExtensions.ActionLink method.
<div class="cart">
#Ajax.ActionLink("Add To Cart", "AddToCart", new { productId = Model.productId }, new AjaxOptions() { HttpMethod = "Post" });
</div>
That MSDN link is must-read for all the possible overloads of this method and parameters of AjaxOptions class. Actually, you can use confirmation, change http method, set OnSuccess and OnFailure clients scripts and so on
If you want to call an action from your JavaScript, one way is to embed your JavaScript code, inside your view (.cshtml file for example), and then, use Razor, to create a URL of that action:
$(function(){
$('#sampleDiv').click(function(){
/*
While this code is JavaScript, but because it's embedded inside
a cshtml file, we can use Razor, and create the URL of the action
Don't forget to add '' around the url because it has to become a
valid string in the final webpage
*/
var url = '#Url.Action("ActionName", "Controller")';
});
});
Javascript Function
function AddToCart(id) {
$.ajax({
url: '#Url.Action("AddToCart", "ControllerName")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'id': id },
success: function (results) {
alert(results)
},
error: function () {
alert('Error occured');
}
});
}
Controller Method to call
[HttpGet]
public JsonResult AddToCart(string id)
{
string newId = id;
return Json(newId, JsonRequestBehavior.AllowGet);
}
You can simply add this when you are using same controller to redirect
var url = "YourActionName?parameterName=" + parameterValue;
window.location.href = url;
You can set up your element with
value="#model.productId"
and
onclick= addToWishList(this.value);
I am using this way, and worked perfectly:
//call controller funcntion from js
function insertDB(username,phone,email,code,filename) {
var formdata = new FormData(); //FormData object
//Iterating through each files selected in fileInput
formdata.append("username", username);
formdata.append("phone", phone);
formdata.append("email", email);
formdata.append("code", code);
formdata.append("filename", filename);
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/InsertToDB');//controller/action
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
//if success
}
}
}
in Controller:
public void InsertToDB(string username, string phone, string email, string code, string filename)
{
//this.resumeRepository.Entity.Create(
// new Resume
// {
// }
// );
var resume_results = Request.Form.Keys;
resume_results.Add("");
}
you can find the keys (Request.Form.Keys), or use it directly from parameters.
You can easily make a <a> link in your view.
<a hidden asp-controller="Home" asp-action="Privacy" id="link"></a>
then in you javascript code use this:
location.href = document.getElementById('link').href;
On a button click, I want to call a Controller method in which I create a PNG image dynamically. I want to then send that image to the view and display it for the user to see. I can't quite figure out how to properly do this, or what I'm exactly doing wrong. My code is as follows:
View
<div style="height:350px; margin:10px;">
<img id="rsDiagram" src="" alt="RS Diagram" class="partDiagram">
</div>
Controller
public ActionResult RSView(string orderNumber)
{
// I create the png and save it to wwwroot/images/
string outfile = Path.GetFullPath(Path.Combine(_hostingEnvironment.WebRootPath, "images", "RSView.png"));
string fileToSend = Convert.ToBase64String(System.IO.File.ReadAllBytes(outfile));
return Json(fileToSend);
}
Javascript
//This is called on a button click
$.ajax({
type: "GET",
url: "/Home/RSView",
data: { "orderNumber": $("#shopOrderNumber").val() },
success: function (response) {
rs.style.display = "block";
$("rsDiagram").attr("src", "data:image/png;base64," + response + '"');
},
error: function (response) {
alert(response.responseText);
}
});
Seems your code is almost alright only little problem founded how you are binding the response on your image tag. Just replace the below line with your older one.
$("#rsDiagram").attr('src', 'data:image/png;base64,' + response);
Note: I have tried to keep all of your existing code.
So the full solution would be looks like
Controller:
Same as yours
public ActionResult RSView()
{
// I create the png and save it to wwwroot/images/
string outfile = Path.GetFullPath(Path.Combine(_hostEnvironment.WebRootPath, "images", "RSView.png"));
string fileToSend = Convert.ToBase64String(System.IO.File.ReadAllBytes(outfile));
return Json(fileToSend);
}
View:
Also same, I just added a button so that anyone can test with this solution
<div style="height:350px; margin:10px;">
<img id="rsDiagram" src="" class="partDiagram">
</div>
<!-- Button for calling ajax request -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Load Images
</button>
Javascript:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
$("button").click(function (e) {
$.ajax({
type: "GET",
url: "/Home/RSView",
//data: { "orderNumber": $("#shopOrderNumber").val() },
success: function (response) {
console.log(response);
$("#rsDiagram").attr('src', 'data:image/png;base64,' + response);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
}
Note: Here in ajax request I have commented your parameter { "orderNumber": $("#shopOrderNumber").val() as I am calling the
controller for the predefined image so that I didn't sent any parameter. Hope you get me here.
Output:
Hope it would resolve your problem.
I've a form composed by a Kendo combobox and a Kendo file upload:
#using (Html.BeginForm("Methode", "controller", FormMethod.Post))
{
<p> Select country </p>
#(Html.Kendo().DropDownList().Name("country")
.DataTextField("Text").DataValueField("Value")
.DataSource(source => { source.Read(read => {
read.Action("GetMonth", "BudgetStage");
});
}))
<p> Select a .CSV file: </p>
#(Html.Kendo().Upload()
.Name("files")
.HtmlAttributes(new { accept = ".csv" })
)
<input type="submit" value="Submit" class="k-button k-primary" />
<input type="button" value="Ajax" class="k-button k-primary" onclick="postData(this)
}
Here is my C# controller code:
public JsonResult methode(IEnumerable<HttpPostedFileBase> files, string country)
{
return Json("It's OK !", JsonRequestBehavior.AllowGet);
}
This works when I click on the submit button, the controller receives files and string values but I need to display the Json returned value from my page.
To do that, I use this ajax function:
function postData(button) {
var form = $(button).parents('form');
if (form.kendoValidator().data("kendoValidator").validate()) {
$.ajax({
type: "POST",
url: form.attr('action'),
data: form.serialize(),
error: function (xhr, status, error) {
alert(error);
},
success: function (response) {
alert(response);
}
});
return false;
}
return false;
}
When I click on the Ajax button, the backend method is call, return the Json value and my JS code display it.
The problem is I receive the string value but not the selected CSV file (null).
How can I send the file and the string and display the returned Json value ?
Thank you in advance.
The problem is that form.serialize() doesn't really work in this scenario. With kendo it shouldn't be different to ASP.NET MVC + JavaScript, so basically, this should help you.
I am making my MVC application. How do I create a button in my view that a click on it will run a function from controller. I would also like to pass data from the view that the button is in. But I do not want to open a different view. I just want to run a function - Button "save to file" would save the table from the view into a file - would open a Directory browser and save a file on a disk.
This will be done with the help of ajax request from your view. You need to add a simple button on your view and call a jquery function on its onclick event like this:
<input type="button" value="save to file" onclick="saveToFile()" />
Then you can create saveToFile function to send ajax request like this: here you can create your data as per your need of fields you want to post to controller. I just adding firstField and secondField for demo:
<script type="text/javascript">
var data = { "firstField" : "value1", "secondField": "value2" };
function saveToFile() {
$.ajax({
url: "/ControllerName/ActionName",
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
success: function (data) {
},
error: function (xhr) {
console.log(xhr);
}
});
});
</script>
Your action method will be like this:
[HttpPost]
public ActionResult UseShippingAddress(string firstField, string secondField)
{
//write your logic here to save the file on a disc
return Json("1");
}
Apparently, the correct solution was to use
#Html.ActionLink("weekly - PDF", "GenerateTable", "Account", new { group_id = Model.group_id, class_id = Model.class_id, type = 1 }, null)
And in GenerateTable method just return a proper file.
I am converting a web form to MVC C# razor project. I like to know how I will get the same functionality in Razor where it will create a link and sumbit the form into the same page. The web form code is -
<asp:LinkButton ID="lnkBtn_1" runat="server" Text='<%#Eval("Sales") %>' OnCommand="LinkButton1_Command" CommandArgument='<%#Eval("Sales") %>' ></asp:LinkButton>
Thanks in advance
Try this
#Html.ActionLink("buttonText", "ControllerAction", "YourController ",
new { #sales = YourModel.Parameter}, new { #class =yourcssclass" })
Your Controller
public class YourController : Controller
{
public ActionResult Index()
{
var model = YourDataToDisplay;
return View(model);
}
public ActionResult ControllerAction(int sales)
{
//.....
}
}
You can use ViewData to define ButtonText.
There are many ways to use link button in rezor ,try any of these
<button type="button" onclick="#("window.location.href='" +#Url.Action("ActionResult", "Controller") + "'")">
Link Button
</button>
<a href="#Url.Action("ActionResult", "Controller")">
Link Button
</a>
#Html.ActionLink("Text","ActionResult","Controller")
submitting form into the same page you have to use Ajax Begin Form or use simple json object with a ajax post method. Try like this
$("#btnSave").click(function (e) {
var urlpath = '#Url.Action("ActionResult", "Controller")';
$.ajax({
url: urlpath ,
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert("Done");
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error !!!");
}
});
You can write an anchor tag. But clicking on the anchor tag usually does not submit the form, but triggers an HTTP GET request. So you need to write some java script to do the form submission.
<form action="Customer/Create">
Submit
</form>
Using jQuery and some unobtrusive javascript code to bind the click event on this anchor tag,
$(function(){
$("#linkToSubmit").click(function(e){
e.preventDefault(); // prevent the normal link click behaviour (GET)
$(this).closest("form").submit();
});
});
Now you can execute the code in your HttpPost action of Create action method in the Customer controller (because that is the form's action set to)
Another option is to keep the submit button inside your form and style it so that it looks like a link as explained in this answer.
if you are new to mvc then you need to check it's basic from MVC tutorials: Please follow below thread for convert your web app code to MVC
https://msdn.microsoft.com/en-us/library/system.web.mvc.html.linkextensions.actionlink(v=vs.118).aspx
#Html.ActionLink("buttonText",new { controller = "ContreollerName", action = "ActionName",
#sales = "Your parameter" })
And then make a action result in your controller