如何将结果发送回同一视图

本文关键字:视图 结果 | 更新日期: 2023-09-27 18:06:14

如果我的视图中有这个:

@using (Html.BeginForm("Sum","Student"))
{
<p>
    Number1:
    @Html.TextBox("num1")
</p>
<P>
    Number2:
    @Html.TextBox("num2")
</P>
<input type="submit" value="Calculate"/>   
}

这个在我的控制器里:

public void Sum(FormCollection values)
{
    var num11 = Convert.ToInt32(values["num1"]);
    var num21 = Convert.ToInt32(values["num2"]);
    int result = num11 + num21;  
    //How return result back to view and show it in a textbox      
}

如何将结果返回到视图并在textbox中显示?

编辑:我按照建议尝试了以下代码,但它随后将我重定向到另一个视图,但没有任何结果。我想在我将数据发送到总和方法的相同视图中显示结果:

public void Sum(FormCollection values)
{
     ....
     ViewBag.result = result;
}

和:

....
 <input type="submit" value="Calculate"/>
    string str = (string)ViewBag.Res;
    @Html.TextBox("Result",str)

如何将结果发送回同一视图

我建议您使用表单模型,而不仅仅是命名字符串。它会让你以更美丽的方式做更多的事情。

视图/Test/Index.cshtml

@model MyForm
@using (Html.BeginForm("Index", "Test"))
{
    <div>@Html.TextBoxFor(m => m.Num1)</div>
    <div>@Html.TextBoxFor(m => m.Num2)</div>
    <div>@Html.TextBoxFor(m => m.Result)</div>
    <input type="submit" value="Calculate" />
}

Myform.cs

public class MyForm
{
    public int Num1 { get; set; }
    public int Num2 { get; set; }
    public long Result => Num1 + Num2;
}

TestController.cs

public class TestController : Controller
{
    [HttpGet]
    public ActionResult()
    {
        return View(new MyForm());
    }
    [HttpPost]
    public ActionResult Index(MyForm form)
    {
        return View(form);
    }
}

更新

看起来我们在这里讨论AJAX请求。尽管我认为在MVC中使用AjaxHelper是一种糟糕的做法(在具有层次结构的大型项目中(,但在这种情况下,它可能会很好地工作。

@using (Ajax.BeginForm("Calculate", "Test", new AjaxOptions
{
    HttpMethod = "GET",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "Result"
}))
{
    <div>@Html.TextBox("num1")</div>
    <div>@Html.TextBox("num2")</div>
    <div id="Result"></div>
    <input type="submit" value="Calculate" />
}

以及方法

public ActionResult Calculate(FormCollection values)
{
    var num1 = Convert.ToInt32(values["num1"]);
    var num2 = Convert.ToInt32(values["num2"]);
    return Content(num1 + num2);
}

别忘了参考js

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
public ActionResult Sum(FormCollection values)
{
    var num11 = Convert.ToInt32(values["num1"]);
    var num21 = Convert.ToInt32(values["num2"]);
    int result = num11 + num21;
    ViewBag.result =result; 
    //How return result back to view and show it in a textbox
     return View();      
}

在你的浏览页面上使用这个ViewBag.result

@Html.TextBox("result ", (string)ViewBag.result) 

使用Jquery Ajax:
您的观点:

 
<body>
		<p>
			Number1:
			@Html.TextBox("num1")
		</p>
		<P>
			Number2:
			@Html.TextBox("num2")
		</P>
		<input type="submit" value="Calculate" id="submit"/>   
	
		<div id="result"></div>
	<!-- JS includes -->
	<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
	
	<script type="text/javascript">
	    $(function () {
	        $("#submit").click(function () {
	            $.ajax({
	                method: "POST",
	                dataType: "json",
	                url: '@Url.Action("Index","Test")',
	                data: { 'num1': $("#num1").val(), 'num2': $("#num2").val() },
	                success: function (result) {
	                    console.log(result);
	                    $("#result").text(result);
	                }
	            });
	        })
	    })
	</script>
</body>

您的控制器:

public class TestController : Controller
{
           [HttpGet]
            public ActionResult Index()
            {
                return View();
            }
            [HttpPost]
            public JsonResult Index(string num1, string num2)
            {
                var num11 = Convert.ToInt32(num1);
                var num21 = Convert.ToInt32(num2);
                int result = num11 + num21;
                return Json(result);
            }
}