Auto update a table on button click - javascript

I have a table in a page. I want to update / reload the table continuously on a button click for every 5 seconds.
The table gets the values from the query running in the model and I don't want duplicate values to be put in the table again.
I also want to stop the reloading of the table on when I click on a another button which is the stop button.
How can I do it? Thanks!

When you click on first button set interval function, which will execute your updating script. And click on other button will clear this interval.
// Click on first button
var flag = setInterval(func, 5000);
// Click on second button
clearInterval(flag);
where func is your updating function

Try that if possible.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using bhanu1.Models;
namespace bhanu1.Controllers
{
public class ranuController : Controller
{
//
// GET: /ranu/
private personEntities1 per = new personEntities1();
public ActionResult Index()
{
return View(per.sandeep1.ToList());
}
//
// GET: /ranu/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: /ranu/Create
public ActionResult Create()
{
return View();
}
//
// POST: /ranu/Create
[HttpPost]
public ActionResult Create([Bind(Exclude = "Id")]sandeep1 san)
{
try
{
// TODO: Add insert logic here
per.AddTosandeep1(san);
per.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /ranu/Edit/5
public ActionResult Edit(int id)
{
return View();
}
//
// POST: /ranu/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /ranu/Delete/5
public ActionResult Delete(int id)
{
return View();
}
//
// POST: /ranu/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}

Related

Passing Values from Checkboxes from View to Controller

I am having trouble passing data from my view to my controller. I am using checkboxes. For my view, I created a class that takes in all my checkboxes (Mon-Fri) and putting them into a list (so I can use the data someplace else). My problem is that when I debug and click the checkboxes on the website, the code does not change whether I click the checkbox or not, so my code doesn't recognize the checkbox data
I'm not sure if I have implemented the View incorrectly but any help to the right direction would be appreciated !
ViewModel:
public List<cDay> _cDays = new List <cDay>();
public List<cDay> cDays
{
get {return _cDays;}
set {_cDays = value;}
}
public class cDay
{
public bool Monday { get; set; }
public bool Tuesday { get; set; }
public bool Wednesday { get; set; }
public bool Thursday { get; set; }
public bool Friday { get; set; }
}
CSHtml file:
#Html.Label("M")
#Html.CheckBox("Monday", false, new { #class = "availability" })
// this is basically the same code for Tuesday-Friday as well.
'<label for="M">M</label> +
'<input class="availability" id="Monday" name="Monday" type="checkbox" value="true">' +
'input name="Monday" type="hidden" value="false">'
// this is basically the same code for Tuesday-Friday, but the "name" corresponds to each day
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(string inputValue, Model viewModel)
{
if(ModelState.IsValid)
//
}
Consider to use the following data model:
public class DaysViewModel
{
public List<CDay> Days { get; set; } = new List<CDay>();
}
public class CDay
{
public CDay()
{
Name = string.Empty;
Selected = false;
}
public CDay(string name)
{
Name = name;
Selected = false;
}
[Required]
public string Name { get; set; }
[Required]
public bool Selected { get; set; }
}
Then you can use the default ASP.NET MVC data binding without a JS support:
#model Models.DaysViewModel
#using (Html.BeginForm("Edit", "Home"))
{
#Html.AntiForgeryToken()
for(int i=0; i < Model.Days.Count; i++)
{
<div class="form-group row">
#Html.CheckBox("Days[" + i + "].Selected", Model.Days[i].Selected)
#Html.Hidden("Days[" + i + "].Name", Model.Days[i].Name)
<span>#Model.Days[i].Name </span>
</div>
}
<input type="submit" value="Save" />
}
And on the server side:
public ActionResult Edit()
{
var model = new DaysViewModel();
model.Days.AddRange( new List<CDay> {
new CDay("Monday"),
new CDay("Tuesday"),
new CDay("Wednesday"),
new CDay("Thursday"),
new CDay("Friday")
});
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(List<CDay> days)
{
if(ModelState.IsValid)
{
// ... you_code here
}
var model = new DaysViewModel() { Days = days };
return View(model);
}
Test screen shots
The view:
On the controller side:
You can do it using jQuery
Add a button bellow your checkboxes
<input type="button" value="Your_Value" class="btn btn-default" />
When click on a button create a post request and sends checked status via querystring
$(document).ready(function () {
$("input[type=button]").click(function () {
var queryString = 'Monday=' + $("input[name=Monday]").is(":checked") + '&Tuesday=' + $("input[name=Tuesday]").is(":checked") + '&Wednesday=' + $("input[name=Wednesday]").is(":checked") + '&Thursday=' + $("input[name=Thursday]").is(":checked") + '&Friday=' + $("input[name=Friday]").is(":checked");
$.ajax({
type: "Post",
url: "/Home/Edit?" + queryString,
success: function (data) {
},
error: function (data) {
}
});
});
});
And inside controller create Edit Post Method like this
[HttpPost]
public ActionResult checkboxespost(string Monday, string Tuesday, string Wednesday, string Thursday, string Friday)
{
...
}

How can I return javascript from a controller actionresult using ContentResult?

I'm wondering how I can return a javascript alert when the file that usually gets generated is not created in the folder. When the else statement is ran, it returns the literal text at the top of the browser tab instead of the alert that I am looking for. It looks like this:
Code:
public ActionResult DownloadFile(string path, string fileName)
{
if (System.IO.File.Exists(path))
{
byte[] fileBytes = System.IO.File.ReadAllBytes(path);
return File(fileBytes, "application/force-download", fileName);
}
else
{
return Content("<script language='javascript' type='text/javascript'>alert('No data was found to create a CSV file!');</script>");
}
}
Firstly you can use the method public virtual ContentResult Content(string content, string contentType); rather than public virtual ContentResult Content(string content);
Controller:
public ActionResult DownloadFile()
{
return Content("alert('No data was found to create a CSV file!');", "application/javascript");
}
In addition,you can also write a result which has a Parametrical constructor and extends ContentResult.You can refer to it
Here is a demo worked:
Controller:
public ActionResult DownloadFile()
{
//return Content("alert('No data was found to create a CSV file!');", "application/javascript");
return new JavaScriptResult("alert('No data was found to create a CSV file!');");
}
public ActionResult DownloadFile1() {
return View();
}
public class JavaScriptResult : ContentResult
{
public JavaScriptResult(string script)
{
this.Content = script;
this.ContentType = "application/javascript";
}
}
DownloadFile1:
#{
ViewData["Title"] = "DownLoadFile1";
}
<h1>DownLoadFile1</h1>
<div>
<partial name="DownLoadFile" />
</div>
#section scripts{
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(function () {
$.getScript("/Test/DownloadFile");
});
</script>
}
Result:

Want to call js method without onclick or onsubmit button of ajax in wicket

I want to call a js method in wicket without using event. For eg, please see below:
public method(Page params) {
Form<?> form = new Form("dataform");
form.add(new AjaxFallbackButton("nextPages", form) {
#Override
public void onSubmit(AjaxRequestTarget target,Form<?> form) {
//do something
}
});
add(form);
}
What I want to achieve is as follow:
public method(Page params) {
Form<?> form = new Form("dataform");
form.add(new AjaxFallbackButton("nextPages", form) {
//do something
});
add(form);
}
I dont want to use setInterval method as I am not sure how much time the user will take to fill the form.
Is there any other way through which I can call the js method?
I did not understand what you want to do exactly, but maybe you can use renderHead method on form creation:
public method(Page params) {
Form<?> form = new Form("dataform"){
#Override
public void renderHead(IHeaderResponse response) {
String js ="your js";
response.render(OnDomReadyHeaderItem.forScript(js));
super.renderHead(response);
}
};
add(form);
}

ASP.NET MVC 4 AJAX.BeginForm and PartialViews

I am considering building a SPA using AJAX.BeginForm, however I am facing an issue when a user has JavaScript disabled, instead of redirecting him to _Layout.cshtml + PartialView.cshtml, it redirects him to just the PartialView.cshtml..
Is there a way to include the Layout and the PartialView in it (where it would be if JavaScript was enabled)?
Thanks
Edit:
Awesome.. Thanks.. I managed to get it working but I am not sure it's the best implementation..
[HttpPost]
public ActionResult Index(Newsletter newsletter)
{
if (ModelState.IsValid)
{
db.Newsletters.Add(newsletter);
db.SaveChanges();
ViewData["message"] = "thanks for signing up to our newsletter!";
if (Request.IsAjaxRequest())
{
return PartialView( "SimpleMessage" );
}
}
return View();
}
And SimpleMessage.phtml is simply just #ViewData["message"];
whereas my View.phtml I have got a condition and checks whether ViewBag["message"] is set or not. If it's set, then it means it's a postback and doesn't show the form and shows the message instead, or else it shows the form:
You can check if Action was called via Ajax, or not, and return different type of result
public ActionResult MyAction()
{
if(Request.IsAjaxRequest()) {
// Html fragment
return PartialView();
}
else {
// Complete HTML page
return View();
}
}
If it's postback, you can pass your model, or simple types (int, string) around as well:
[HttpPost]
public ActionResult MyAction(Model model)
{
if(Request.IsAjaxRequest()) {
// Html fragment
return PartialView(model);
}
else {
// Complete HTML page
return View(model);
}
}
Edit: In your specific case I would do like this, but it's only my preference.
[HttpPost]
public ActionResult Index(Newsletter newsletter)
{
if (ModelState.IsValid)
{
db.Newsletters.Add(newsletter);
db.SaveChanges();
if (Request.IsAjaxRequest())
return PartialView("SimpleMessage");
else
return View("SimpleMessage")
}
if (Request.IsAjaxRequest())
return PartialView(newsletter);
else
return View(newsletter);
}

How to stop an MVC RedirectToRouteResult JavaScript?

I am designing a site and am trying to be compatible with javascript turned off or on.
I have a Controller Action named as follows...
public RedirectToRouteResult AddWorkAssignment(int id)
{
// delegate the work to add the work assignment...
return RedirectToAction("Index", "Assignment");
}
and my jQuery I do a post
$('#someButton').click(function() {
var id = $('#whereTheIDIs').val();
$.post('/Assignment/AddWorkAssignment/' + id);
return false;
});
but the RedirectToAction on the controller will do just that.... how do I stop the redirect to occur, or how do I structure the controller and page to handle this, because I want the redirect to occur if javascript is turned off.
Change your controller to something like this:
public ActionResult AddWorkAssignment(int id)
{
// do work to add the work assignment....
if (Request.IsAjaxRequest())
return Json(true);
return RedirectToAction("Index", "Assignment");
}
You could create your own filter attribute too... much like the AcceptVerbs attribute.
HTHs
Charles
EDIT: AjaxRequest ActionMethodSelectorAttribute attribute
Kickstart from here
public class AjaxRequest : ActionMethodSelectorAttribute
{
public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
{
if (controllerContext == null)
throw new ArgumentNullException("controllerContext");
return controllerContext.HttpContext.Request.IsAjaxRequest();
}
}
Then your controller:
public RedirectToRouteResult AddWorkAssignment(int id)
{
// do work to add the work assignment....
return RedirectToAction("Index", "Assignment");
}
[AjaxRequest]
public JsonResult AddWorkAssignment(int id)
{
// do work to add the work assignment....
return Json(true);
}

Categories

Resources