1

I have an MVC application that will list names. The names are in an entity framework database. A timer is beside the first name in the list and when the timer ends, the name is removed from the list and the timer begins again for the next record (this continues until no names are left).

I also have the ability to add names to the list. Right now when a user adds a name to the list by clicking on the create link, the name is added but it restarts the current timer that is counting down. I need the name to be added without refreshing the timer. Is that possible??

View:

@model IEnumerable<RangeTimer.Models.UserName>

@{
    ViewBag.Title = "ABC";
}
<div class="jumbotron">

<p>
        @Html.ActionLink("Add Name to list for range time", "Create")
    </p>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.FullName)
        </th>
        <th>
            Time Remaining
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td id="FullName">
                @Html.DisplayFor(modelItem => item.FullName)
            </td>
            <td>
                <span id="timer"></span>
            </td>
        </tr>
    }

</table>

</div>
<br/>
<script language="javascript" type="text/javascript">

$(document).ready(function () {
    startTimer();
    function startTimer() {           
        $('#timer').countdown({
            layout: '{mnn} : {snn}', timeSeparator: ':', until: 15, onTick: TimerColorChange, onExpiry: restartTimer

        });            
    }

    function restartTimer() {          
        $('#timer').countdown('destroy');

        var currentName = $('#FullName').Text;

        //we delete the table's Info
        var deleteRecord = $('#FullName').parent().remove();

        // deleteRecord.deleteRow(); //commented out since this also removes my timer

        var action = '@Url.Action("DeleteName","Controller")';
        $.get(action + "?name=" + currentName).done
            (function (result) {
                if (result) {
                    //  your user is deleted
                }
            })
        startTimer();
    }

    function TimerColorChange(periods) {
        var seconds = $.countdown.periodsToSeconds(periods);
        if (seconds <= 3) {
            $(this).css("color", "red");
        } else {
            $(this).css("color", "black");
        }
    }
});


</script>  

Controller

  // GET: UserNames
    public ActionResult Index()
    {
        return View(db.UserNames.ToList());
    }

    // GET: UserNames/Details/5
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        UserName userName = db.UserNames.Find(id);
        if (userName == null)
        {
            return HttpNotFound();
        }
        return View(userName);
    }

    // GET: UserNames/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: UserNames/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,FullName")] UserName userName)
    {
        if (ModelState.IsValid)
        {
            db.UserNames.Add(userName);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(userName);
    }
Ivan Gritsenko
  • 3,910
  • 2
  • 17
  • 30
user2448412
  • 75
  • 1
  • 10
  • Possible duplicate: [jQuery AJAX submit form](http://stackoverflow.com/a/6960586/1260204). Also your HTML is missing the id and name that you want to post to the server. Finally if you want to execute the Create function then it should not redirect but return an Http result (200 = ok, other id = error) so you need to either modify your server code OR use a WebAPI for actions which would be a better design. – Igor Mar 04 '16 at 19:41
  • It restart the counter because 'Create' is a link which redirect you to a new page to create the name, then back to the `Index` method (your script stopped running as soon as you left the page, and its starts again when you render it again). Use ajax to post the value so you do not leave the page (or pass a value along each get/post redirect that indicates the timer status so that you can use it when the `Index` page is rendered) –  Mar 05 '16 at 07:25

2 Answers2

1

If you are send time parameter to addname action, and must add redirect paramater. And than use viewbag.time.

0

Yes, this is possible! Through the magic of Ajax and Javascript/jQuery, you can call your controller when adding a name via ajax to submit the name and return the added name and append it to the page using Javascript or jQuery. Unfortunately, this is a little complex and I can't write it out for you at the moment. However, try some of these links.

https://msdn.microsoft.com/en-us/library/dd381533(v=vs.100).aspx

Making a Simple Ajax call to controller in asp.net mvc

Good luck!

EDIT: Here's a small sample of a javascript function using jQuery/ajax

function AddName(name) {
    $.ajax({
        url: action, // Make it whatever your controller is
        data: { UserName: name }, // or whatever object you need
        type: "POST",
        dataType: "html",
        success: function (result, status, blah) {

            if (result) {
                AppendRow(result, target); // Create function to add to your name list
            }
        },
        error: function (result) {
            AjaxFailed(result, result.status, result.error);
        }
    });
}
Community
  • 1
  • 1
Blue Eyed Behemoth
  • 3,049
  • 1
  • 14
  • 23