[英]How can I pass a ViewModel property to an ajax post method?
function ResendEmailInvite(internalUserId, familyMemberId) {
theinternalUserId = internalUserId;
theFamilyMemberId = familyMemberId;
if(confirm('Are you sure you want to resend this family member's invite?')){
$.ajax({
type: "POST",
url:"/Admin/ResendFamilyMemberEmail",
data: {internalUserId : theinternalUserId, familyMemberId : theFamilyMemberId},
success: function(response){
alert(response);
},
error: function(){
alert("Error");
}
});
return false;
}
}
I am using ASP.net MVC 3. This is an ajax/javascript method in my view. 我正在使用ASP.net MVC3。在我看来,这是ajax / javascript方法。
As far as the syntax goes, is this correct? 就语法而言,这是正确的吗?
The familyMemberId
is going to be dynamic, however, the userId
is not. familyMemberId
将是动态的,但是userId
不是。 I want to pass the userId
from my viewModel to this ajax call, how can I do this? 我想将userId
从我的viewModel传递到此ajax调用,该怎么做?
What you're wanting to do is get the data from the model in your controller into the view. 您要做的是将控制器中模型的数据放入视图中。 This is what MVC is all about. 这就是MVC的全部意义。 From the MSDN MVC 4 Tutorial : 从MSDN MVC 4教程 :
You can define your model using the VS menu system and the Entity Framework so you're actually accessing the database. 您可以使用VS菜单系统和Entity Framework定义模型,以便实际访问数据库。
public class YourController : Controller
{
private YourDBContext db = new YourDBContext();
public ActionResult YourAction(int user_id = 0)
{
User user = db.Users.find(user_id);
if(user == null) {
return HttpNotFound(); // Or unauthorized or whatever
}
return View(user);
}
//...
@Model IEnumerable<MvcUser.Models.User>
<!-- other stuff -->
<script type="text/javascript>
// the rest of your script
function ResendEmailInvite(internalUserId, familyMemberId) {
theinternalUserId = @Model.userId;
theFamilyMemberId = familyMemberId;
if(confirm('Are you sure you want to resend this family member's invite?')){
$.ajax({
type: "POST",
url:"/Admin/ResendFamilyMemberEmail",
data: {internalUserId : theinternalUserId, familyMemberId : theFamilyMemberId},
success: function(response){
alert(response);
},
error: function(){
alert("Error");
}
});
return false;
}
}
This works because, as you pointed out, the userId is not dynamic after the page has loaded. 如您所指出的,这之所以可行是因为页面加载后,userId不是动态的。 You would need to create some other hook in your HTML for javascript to grab if you wanted really dynamic behavior. 如果您想要真正的动态行为,则需要在HTML中创建一些其他的钩子以供JavaScript抓取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.