我有一个显示一组图像的视图。我希望能够选择一个图像并将其Id传回控制器。如何使用jQuery选择图像?我是使用MVC框架的新手。
以下是我的观点,
<html>
<head>
<title>Select User</title>
@model xxxx.xxxx.xxxx.UserViewModel
</head>
<body>
<div class="divWrapper">
<h1 align="center">Select a User</h1>
<br />
<div class="imageHolder">
@for (int i = 0; i < Model.Users.Length; i++)
{
<figure class="FigureAlign">
<img class="imageBorder" src="@Url.Content(@System.Web.Configuration.WebConfigurationManager.AppSettings["imagePath"])" width="350" height="350" />
</figure>
}
</div>
</div>
</body>
</html>
这是我的UserViewModel,
public class UserViewModel
{
public User[] Users { get; }
public UserViewModel(User[] users)
{
this.Users = users;
}
public class User
{
public int Id { get; }
public string Name { get; }
public string ImagePath { get;}
public User(int id,string name, string imagePath)
{
this.Id = id;
this.Name = name;
this.ImagePath = imagePath;
}
}
}
答案 0 :(得分:0)
这是一个例子。
$(document).ready(function(){
$(".imageContainer img").click(function(){
// here we bind the click event to the image
if ($(this).hasClass("selected"))
$(this).removeClass("selected"); // deselect the image
else $(this).addClass("selected"); // select the image
});
/// lets save the images and send its data to the backend
function Save(){
var selectedImages= []
$.each($(".imageContainer img"), function(){
if ($(this).hasClass("selected"))
selectedImages.push($(this).attr("objectId"));
});
/// now that we have the selected items we should send it to the backend using ajax
$.ajax({
contentType: "application/json",
dataType: "json",
type: "POST",
async: false,
data: JSON.stringify(selectedImages),
url: "/save",// this is a test , this method should have a List<int> parameter becouse selectedImages is List<int>
success: function (data) {
// now reset the selected images
$(".imageContainer img").removeClass("selected");
}
});
}
});
&#13;
img{
width: 100px;
height:100px;
}
.selected{
border:1px solid red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="imageContainer">
<img objectId="1" src="https://www.w3schools.com/w3css/img_lights.jpg" />
<img objectId="2" src="https://www.w3schools.com/w3css/img_fjords.jpg" />
</div>
&#13;