.NET MVC在创建新记录时阻止刷新

时间:2016-03-04 19:29:15

标签: c# asp.net-mvc jquery-countdown

我有一个MVC应用程序,它将列出名称。名称位于实体框架数据库中。计时器位于列表中的第一个名称旁边,当计时器结束时,名称将从列表中删除,计时器将再次开始下一个记录(这将一直持续到没有名字留下)。

我还可以在列表中添加名称。现在,当用户通过单击创建链接向列表添加名称时,会添加名称,但会重新启动正在倒计时的当前计时器。我需要添加名称而不刷新计时器。那可能吗?

查看:

@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>  

控制器

  // 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);
    }

2 个答案:

答案 0 :(得分:1)

如果您要向addname操作发送时间参数,则必须添加重定向参数。而不是使用viewbag.time。

答案 1 :(得分:0)

是的,这是可能的!通过Ajax和Javascript / jQuery的魔力,您可以在通过ajax添加名称时调用您的控制器以提交名称并返回添加的名称并使用Javascript或jQuery将其附加到页面。不幸的是,这有点复杂,我暂时无法为你写出来。但是,请尝试其中一些链接。

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

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

祝你好运!

编辑: 这是使用jQuery / ajax

的javascript函数的一小部分示例
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);
        }
    });
}