从控制器更新Textarea

时间:2017-08-01 09:20:53

标签: asp.net-mvc-4 signalr

我想在找到一些结果并且页面不应该重新加载后从控制器更新textarea。对此有什么解决方案吗?

public class HomeController : Controller
{
   public ActionResult Index()
   {
        return View();
   }

    public JsonResult SolveProblems(Problem[] array){

            Solution sol=new Solution(array);

            sol.OnSolutionFound+=sol_OnSolutionFound;
            sol.OnTaskComplete+=sol_OnTaskComplete;

            sol.Start();
            return Json("Process started");
    }

    private void sol_OnSolutionFound(object sender, SolutionFoundEventArgs e)
    {
        // Here i want update textarea 
    }

    private void sol_OnTaskComplete(object sender,  SolutionCompletedEventArgs e)
    {
       // Here i want show process is finished  
    }       
}

这是我的html页面。其中包含一些代码和一个textarea

..... some code....

<textarea class="form-control" id="ResultDisplay"></textarea>
<button type="button" id="btnSolve" class="btn btn-primary">Solve</button>

这是我的javascript文件

 function GetProblems(){
     ...code... 
     return array; 
 }

 $("#btnSolve").click(function () {

    $.ajax({
        type: "POST",
        url: "/Home/SolveProblems",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(GetProblems()),
        dataType: "json",

        success: function (response) {

        },
        error: function (response) {
            alert("Unexpected error occurs!")
        }
    });
 });

1 个答案:

答案 0 :(得分:0)

所以,我已经使用SignalR解决了我的问题,因为freedomn-m告诉我要做

我需要创建一个Hub,使用i可以在sol_OnSolutionFound被触发时发送数据。

这是我的中心

public class SolutionHub : Hub
{
    public void SolutionFound(string Solution)
    {
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<SolutionHub>();
        hubContext.Clients.All.addNewMessageToPage(Solution);
    }
}

在Index.cshtml中添加部分

@section scripts {
<!--Script references. -->
<!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-2.2.2.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script>
    $(function () {
        // Reference the auto-generated proxy for the hub.
        var chat = $.connection.solutionHub;
        // Create a function that the hub can call back to display messages.
        chat.client.addNewMessageToPage = function (Solution) {
            // Add the message to the page.
            $("#ResultDisplay").append(Solution);
        };

        $.connection.hub.start().done(function () {
        });
    });
</script>
}

最后需要在SolutionFound被解雇时致电sol_OnSolutionFound

private void sol_OnSolutionFound(object sender, SolutionFoundEventArgs e)
{
    SolutionHub Hub=new SolutionHub();
    Hub.SolutionFound(e.Solution);
}