我正在使用 ASP.NET MVC 3。我有一个问题,是否可以更新模型,即使它没有被发送到 Controller ?也许问题是完整的,或者我以错误的方式做事?
我有一个 Controller 方法的 ajax 调用。我正在传递一个ID。我希望 Controller 在数据库中找到一些东西,然后更新模型,将其传递回 View 。
我有一个相当大的模型...我找到了一些解决方案,将模型转换为 javascript 对象,并将其发送到 Controller 。那是唯一/正确的方法吗?
How to send a model in jQuery $.ajax() post request to MVC controller method
我想也许 Controller 有模型,我可以在其中更新一些字段?
对 Controller 的调用:
function getBis(id) {
$.ajax({
type: "GET",
url: '@Url.Action("GetBis")',
data: { "id": id },
dataType: 'json',
cache: false,
success: function (data) {
// Do something here
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Problem!");
}
});
}
Controller 代码:
public ActionResult GetBis(string id)
{
BeslutIStortDTO viewModel = new BeslutIStortDTO();
int theId;
if (!Int32.TryParse(id, out theId))
throw new Exception("Wrong id");
viewModel = _blLayer.GetBIS(theId);
// somehow update the model here!
return View("index", viewModel);
}
最佳答案
通常,当您需要“反射(reflect)”UI 上发生的更改而不进行任何映射时,您通常会在 JQuery 和 Controller 之间“传递模型”(MVC 足够聪明,可以根据您提供的参数构造一个新对象) .在你的情况下,你说你只需要传递一个 ID 就可以在你的模型上做一些事情。因此,您需要做的就是将 ID 作为参数传递,在 Controller 操作中获取它,然后执行您的操作。
看看下面的链接
关于c# - 更新 Controller 中的模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10410831/