Reputation: 301
I'm trying to make a method run once a user clicks a button on a page. I created a sample of code to test it but it doesn't work, though it may be because I'm using MessageBox.
<input id="upload-button" type="button" ondblclick="@ModController.ShowBox("Message");" value="Upload"/><br />
Here's the method I'm invoking.
public static DialogResult ShowBox(string message)
{
return MessageBox.Show(message);
}
Any idea on how I can make this function properly?
Upvotes: 1
Views: 360
Reputation: 3990
You could do something like this if your intent is to pass a message to the client and display a dialog:
In your view, add the following:
@using (Html.BeginForm("ShowBox","Home",FormMethod.Post, new { enctype = "multipart/form-data" })){
@Html.Hidden("message", "Your file has uploaded successfully.");
<input id="upload-button" type="submit" value="Click Me" />
<input id="file" name="file" type="file" value="Browse"/>
}
Then in your controller:
[HttpPost]
public ActionResult ShowBox(string message, HttpPostedFileBase file)
{
if (file == null || file.ContentLength == 0)
{
//override the message sent from the view
message = "You did not specify a valid file to upload";
}
else
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/Uploads"));
file.SaveAs(path);
}
System.Text.StringBuilder response = new System.Text.StringBuilder();
response.Append("<script language='javascript' type='text/javascript'>");
response.Append(string.Format(" alert('{0}');", message));
response.Append(" var uploader = document.getElementById('upload-button'); ");
response.Append(" window.location.href = '/Home/Index/';");
response.Append("</script>");
return Content(response.ToString());
}
NOTE: I think this approach is less than ideal. I'm pretty sure that returning JavaScript directly like this from the controller is probably some sort of an anti-pattern. In the least, it does not feel right, even thought it works just fine.
Upvotes: 2
Reputation: 1233
It looks like you're using a Razor template. If so, and you're using MVC, I don't think you're approaching this right. MVC doesn't work on an event system like ASP.NET. In MVC you make a requst to an ACtion method, usually with a URL in the form of {controller}/{action}, or something like that.
you have few options:
Setup a javascript event for the dblClick event, and perform an AJAX request to the server in the event handler.
Use @ActionLink() and style it to look like a button.
If you are using ASP.NET, there are certain POST parameters you can set before posting to the server, which will tell ASP.NET to run a certain event handler. However, if you're using ASP.NET, I'd recommend using web forms instead of Razor. I've never used Razor with ASP.NET myself, but I don't think the two technologies Jive very well.
Upvotes: 1