dan*_*dan 57 javascript ajax asp.net-mvc jquery razor
我知道这是一个非常基本的问题.
但是你可以告诉我所有可用的选项,
从Razor View
调用控制操作方法[通常是任何服务器端例程],并且
在哪些情况下最适合用于.
谢谢.
Sam*_*ath 96
方法1:使用jQuery Ajax获取调用(部分页面更新).
适用于需要从数据库中检索jSon数据的情况.
控制器的行动方法
[HttpGet]
public ActionResult Foo(string id)
{
var person = Something.GetPersonByID(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)
Jquery GET
function getPerson(id) {
$.ajax({
url: '@Url.Action("Foo", "SomeController")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: { id: id },
success: function(person) {
$('#FirstName').val(person.FirstName);
$('#LastName').val(person.LastName);
}
});
}
Run Code Online (Sandbox Code Playgroud)
人类
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
方法2:使用jQuery Ajax Post调用(部分页面更新).
适用于需要将部分页面发布数据导入数据库的情况.
Post方法也和上面一样只是替换 [HttpPost]Action方法和类型post为jquery方法.
有关更多信息,请在此处检查将JSON数据发布到MVC控制器
方法3:作为表单发布方案(整页更新).
适用于需要将数据保存或更新到数据库的情况.
视图
@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{
@Html.TextBoxFor(model => m.Text)
<input type="submit" value="Save" />
}
Run Code Online (Sandbox Code Playgroud)
行动方法
[HttpPost]
public ActionResult SaveData(FormCollection form)
{
// Get movie to update
return View();
}
Run Code Online (Sandbox Code Playgroud)
方法4:作为表单获取方案(整页更新).
适用于需要从数据库获取数据的情况
获取方法也与上面相同,只需替换 [HttpGet]Action方法和FormMethod.GetView的form方法.
我希望这会对你有所帮助.