I have create web app in MVS 3
but failed to display alert message after data insert into database
Controller code:
[HttpPost]
public ActionResult QuestionBank(QuestionBank questionbank)
{
if (ModelState.IsValid)
{
dbEntities.QuestionBanks.AddObject(questionbank);
dbEntities.SaveChanges();
//questionbank.SendEnquiryEmail(questionbank);
ViewData["Message"] = "Data inserted";
return RedirectToAction("QuestionBank");
}
return View(questionbank);
}
Used ViewData["Message"] = "Data inserted"; which is not displayed message :(
whats going wrong or i placed it somewhere else?
OR ELSE I MAY HAVE THIS CODE
<script type="text/javascript">
//i'm using jquery ready event which will call the javascript chunk after the page has completed loading
$(document).ready(function () {
//assuming that your variable name from the code behind is bInsertSuccess
var bSuccess = "<%= myvar %>";
if (bSuccess) {
alert("Successfully Inserted");
}
});
</script>
but i dont know where i declare that variable myvar which checks insertion plz help
On your .chsthml page:
<script type="text/javascript">
$(document).ready(function () {
var msg = '#ViewBag.Message';
alert(msg);
});
</script>
in your action:
ViewBag.Message = "1";
Edit: Apply conditional check in script:
<script type="text/javascript">
$(document).ready(function () {
var msg = '#ViewData["Message"]';
if(msg=='1')
alert("you are done with your thing");
});
</script>
In view:
ViewData["Message"] = "1";
ViewData["Message"] would result in same thing here.
Try to user
TempData
instead of
ViewData
Related
I have a LINQ query which gets the Type and count of types, and I have it in my controller. In my view I am using a Pie Chart from Google Charts and I am trying to display the data acquired by the LINQ statement. However, when I run the program the Pie Chart doesn't display. No errors appear though. So I am struggling to see whether my problem is my View or the Controller
Controller:
public ActionResult Report_5()
{
return View();
}
public ActionResult GetChart5()
{
var result = from x in db.Submission
group x by x.Type into grp
select new
{
Type = grp.Key,
Count = grp.Count()
};
return Json(result, JsonRequestBehavior.AllowGet);
}
Report_5 View:
<h2 style="text-align:center">Type Count</h2>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawTable() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Type');
data.addColumn('string', 'Count');
$.getJSON("#Url.Action("GetChart5")", null, function (chartData) {
$.each(chartData, function (i, item) {
data.addRow([item.Type, item.Count]);
});
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
});
}
</script>
<div id="donutchart" style="width: 900px; height: 500px;"></div>
Please let me know if I need to provide more information.
I made the following:
1. created view in folder Models.
public class ModelSubmission
{
public string Type { get; set; }
public int TotalSubmissions { get; set; }
}
In home controller created the following:
public ActionResult Report_5()
{
return View();
}
public ActionResult GetChart5()
{
List<ModelSubmission> result = new List<ModelSubmission>();
result.Add(new ModelSubmission() { Type="Book", TotalSubmissions = 3 });
result.Add(new ModelSubmission() { Type = "Book chapter", TotalSubmissions = 7 });
result.Add(new ModelSubmission() { Type = "Journal Article", TotalSubmissions = 3 });
return Json(result, JsonRequestBehavior.AllowGet);
}
And then copy/pasted your view. Then executed for debugging, and as you mentioned seen nothing special. After clicking F12 in chrome I noticed following error message:
Uncaught ReferenceError: drawChart is not defined.
It lead me to conclusion, that in your code instead of
google.setOnLoadCallback(drawChart);
you should write
google.setOnLoadCallback(drawTable);
After some debugging I noticed other errors in your code. Try to find them while watching the following view:
<h2 style="text-align:center">Type Count</h2>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"> </script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"> </script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawTable);
function drawTable() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Type');
data.addColumn('number', 'Count');
$.getJSON("#Url.Action("GetChart5")", null, function (chartData) {
$.each(chartData, function (i, item) {
data.addRow([item.Type, item.TotalSubmissions]);
});
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
var options = {
'title': 'Forgotten input',
'width': 400,
'height': 300
};
chart.draw(data, options);
});
}
You should be more careful when copy/paste code from other pages
I'm trying to create an autocomplete text box using Jquery UI.
I can see that GetActiveItems works fine and i got a json result , but I can't see the autocomplete on the screen. I think that the problam is in the 'OnActionExecuted' when the ActionResult is being execute.
Please help me :)
thanks,
Siri
View:
<input type="text" id="mpvalue" name="mpvalue" />
<script type="text/javascript">
$(document).ready(function () {
$('#mpvalue').autocomplete({
source: '#Url.Action("GetActiveItems")'
});
})
</script>
Controller:
public ActionResult GetActiveItems(string term)
{
var result = from e in db.Items
where (e.IsBlock != true) && (e.Description.ToLower().Contains(term))
select e.Description;
return Json(result, JsonRequestBehavior.AllowGet);
}
I upload a Html file with Dropzone.js, as into site examples :
//Upload view
#using System.Text;
#{
Layout = null;
string path = ViewBag.path;
}
#if (String.IsNullOrEmpty(fileName))
{
#Styles.Render("~/Content/css")
#Styles.Render("~/Content/themes/base/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/bootstrap")
#Scripts.Render("~/bundles/dropzone")
<form action="#Url.Action("Upload", "Home")" class="dropzone" id="dropzoneJsForm"></form>
<button id="submit-all">Submit All Files</button>
<script type="text/javascript">
Dropzone.options.dropzoneJsForm = {
//prevents Dropzone from uploading dropped files immediately
autoProcessQueue: false,
init: function () {
var submitButton = document.querySelector("#submit-all");
var myDropzone = this; //closure
submitButton.addEventListener("click", function () {
//tell Dropzone to process all queued files
myDropzone.processQueue();
});
}
};
</script>
}
else
{
#Html.Raw(System.Web.HttpUtility.HtmlEncode(File.ReadAllText(path)))
}
//HomeController
public ActionResult Upload()
{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
if (file.ContentLength > 0)
{
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
ViewBag.path = path;
}
}
return View();
}
The file was saved,the view can read it but the page did not display anything.
I can not figure out what's not working. If I active the debugger seems that everything is ok but in the end the page did not draw the html tag of the file. Can you help me or suggest a possible solution
Thank you so much
Instead HttpUtility.HtmlDecode, can you please check HttpUtility.UrlDecode, assuming your file is pure html, not html characters.
I'm trying to implement the autocomplete function in my website, but won't work properly.
Here is the code of my view:
<script src="~/Scripts/jquery-ui-1.8.20.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-ui-1.8.20.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#SearchString").autocomplete({
source: "/Test/AutocompleteSuggestions",
minLength: 1,
select: function (event, ui) {
if (ui.item) {
$("#SearchString").val(ui.item.value);
$("form").submit();
}
}
});
});
</script>
#using (Html.BeginForm())
{
<p>
Find by name: #Html.TextBox("SearchString")
<input type="submit" value="Search" /></p>
}
Here is code of my autoComplete controller action:
public JsonResult AutocompleteSuggestions(string searchstring)
{
var suggestions = from s in db.Students
select s.Name;
var namelist = suggestions.Where(n => n.ToLower().StartsWith(searchstring.ToLower()));
// return namelist.ToList();
return Json(namelist, JsonRequestBehavior.AllowGet);
}
Can anyone help me ?
Thanks in advance
you are trying to pass IQueryable. try replacing it with
return Json(namelist.ToList(), JsonRequestBehavior.AllowGet);
if that still doesnt work.
try replacing "searchString" to "term"
public JsonResult AutocompleteSuggestions(string term)
Ive read an article that you must use the "term" query string. but Im not pretty sure about it.
I have an ASP.NET MVC app that opens a "Request" view in a new browser window. When the user submits the form, I'd like the window to close. What should my RequestController code look like to close the window after saving the request information? I'm not sure what the controller action should be returning.
You could return a View that has the following javascript (or you could return a JavaScript result) but I prefer the former.
public ActionResult SubmitForm()
{
return View("Close");
}
View for Close:
<body>
<script type="text/javascript">
window.close();
</script>
</body>
Here is a way to do it directly in your Controller but I advise against it
public ActionResult SubmitForm()
{
return JavaScript("window.close();");
}
Like such:
[HttpPost]
public ActionResult MyController(Model model)
{
//do stuff
ViewBag.Processed = true;
return View();
}
The view:
<%if(null!=ViewBag.Processed && (bool)ViewBag.Processed == true){%>
<script>
window.close();
</script>
<%}%>
It sounds like you could return an almost empty View template that simply had some javascript in the header that just ran "window.close()".
You can close by this code:
return Content(#"<script>window.close();</script>", "text/html");
This worked for me:
[HttpGet]
public ActionResult Done()
{
return Content(#"<body>
<script type='text/javascript'>
window.close();
</script>
</body> ");
}
This worked for me to close the window.
Controller:
return PartialView("_LoginSuccessPartial");
View:
<script>
var loginwindow = $("#loginWindow").data("kendoWindow");
loginwindow.close();
</script>
Using this you can close the window like this:
return Content("<script language='javascript'>window.close();</script>");