如何将结果发送回同一视图? [英] How can I send result back to the same view?
问题描述
如果我的视图中有此内容:
If I have this in my View:
@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
}
如何将结果返回到视图并显示在文本框
中?
How can I return the result back to the view and show it in a textbox
?
编辑:我按照建议尝试了以下代码,但随后将我重定向到另一个视图,但没有任何结果.我想在将数据发送到sum方法的同一视图中显示结果:
Edit: I tried the following code as suggested but it then redirect me to another view without any result. I want to show the result in the same view that I send the data to the sum method:
public void Sum(FormCollection values)
{
....
ViewBag.result = result;
}
并且:
....
<input type="submit" value="Calculate"/>
string str = (string)ViewBag.Res;
@Html.TextBox("Result",str)
推荐答案
我建议您使用表单模型而不是仅使用命名字符串.它可以让您以更漂亮的方式做更多的事情.
I would suggest you to use form-model instead of just named strings. It will allow you to do much more in much more beautiful way.
Views/Test/Index.cshtml
Views/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
Myform.cs
public class MyForm
{
public int Num1 { get; set; }
public int Num2 { get; set; }
public long Result => Num1 + Num2;
}
TestController.cs
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是一种不好的做法(在具有层次结构的大型项目中),但在这种情况下,它可能会很好地工作.
Looks like we're talking about AJAX requesting here. Although i consider using AjaxHelper at MVC a bad practice (in a large projects with hierarchycal structure), in this case it might work just fine.
@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>
这篇关于如何将结果发送回同一视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!