我有一个带有文本框的视图,当我输入并输入服务编号时,它应该从数据库中检索数据并在同一视图中的标签中显示这些数据,此应用程序是ASP.net MVC应用程序。有人可以告诉我如何做到这一点。感谢
更多 我可以在没有javascript的情况下调用控制器方法
是否可以在视图中调用控制器方法并在同一视图中显示结果 如果可以告诉我该怎么做,谢谢
答案 0 :(得分:0)
你可以使用AJAX。让我们举个例子:
@Html.LabelFor(x => x.FooBar, htmlAttributes: new { id = "fooBarLabel" })
@Html.TextBoxFor(x => x.FooBar, new { id = "fooBar", data_url = Url.Action("CalculateValue") })
然后在单独的javascript文件中,您可以订阅文本字段的.change
事件并触发对控制器操作的AJAX调用:
$(function() {
$('#fooBar').change(function() {
var url = $(this).data('url');
var value = $(this).val();
$('#fooBarLabel').load(url, { value: value });
});
});
并且剩下的就是相应的控制器操作:
public ActionResult CalculateValue(string value)
{
// The value parameter will contain the text entered by the user in the text field
// here you could calculate the value to be shown in the label based on it:
return Content(string.Format("You entered: {0}", value));
}