i want to call a jquery alert box in the mvc 4 controller but how to i do that?
heres my jquery code in my razor.cshtml
$( function errMsgBox()
{
alert( "Please select the Correct Activity and Task" );
window.location = "/Memory/Create";
} );
heres my controller codes
catch (Exception ex2)
{
return View("Create");
~~here is i want to call the jquery method~~
}
You cannot use Javascript within the controller. If you want to pass the error message into the page, then you have to use the ViewBag
or a return model.
Here's a quick ViewBag
example: In the controller
protected ActionResult Index()
{
ViewBag.ErrorMessage = "";
//some code
try
{
//more code
} catch(Exception ex)
{
ViewBag.ErrorMessage = "alertError('" + ex.Message + "');";
}
return View();
}
In a Razor view:
<script type="text/javascript">
function alertError(msg) {
alert(msg);
//some code
}
@ViewBag.ErrorMessage
</script>
Similar to what @NewAmbition suggested, to call it after the page completes loading:
<script type="text/javascript">
function alertError(msg) {
alert(msg);
//some code
}
$(function() {
@ViewBag.ErrorMessage
});
</script>
In the controller:
catch (Exception ex2)
{
ViewBag.ErrorMsg = "Any string you want";
return View("Create");
}
Then in View "Create":
@if(ViewBag.ErrorMsg == "Any string you want")
{
<script type="text/javascript">
alert( "Please select the Correct Activity and Task" );
</script>
}
I hope this works for you.
You can try somthing like this, if is ok javascript too.
public ActionResult Index() {
var script = "alert('Message from Server');";
return JavaScript(script);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.