使用复选框值发送到控制器
问题描述:
图像呈现Razor视图页面上这样使用复选框值发送到控制器
<img id="9" class="thumb" src="/Content/uploads/Jellyfish.jpg">
<img id="10" class="thumb" src="/Content/uploads/Lighthouse.jpg">
<img id="11" class="thumb" src="/Content/uploads/Chrysanthemum.jpg">
我怎样才能把复选框上的每个图像的边对这些图像的ID发送到进一步的操作控制器?
答
您可以编写代码类似:
的Html
<div>
<img id="9" class="thumb" src="/Content/uploads/Jellyfish.jpg">
<input type='checkbox' class='sendImage' /></div>
<div>
<img id="10" class="thumb" src="/Content/uploads/Lighthouse.jpg">
<input type='checkbox' class='sendImage' /></div>
<div>
<img id="11" class="thumb" src="/Content/uploads/Chrysanthemum.jpg">
<input type='checkbox' class='sendImage' /></div>
JS
$(".sendImage").bind("change", function(e){
var checkbox = $(e.target);
if(checkbox.is(":checked")){
var imageId = checkbox.siblings('img').attr("id");
alert("checked image id : " + imageId);
//send image id to your controller for further processing
}
});
这里是working fiddle。
答
您可以在服务器上执行此操作:
public ActionResult SaveImageId(string imageId)
{
//Process your image id somewhere
//If successful
return Json(new { success = true }, JsonRequestBehaviours.AllowGet);
}
在客户端:
$(".sendImage").change(function(){
var imageId = $(this).is(":checked")
? $(this).siblings('img').attr("id")
: null;
if(imageId) sendRequest(imageId);
});
//Send the image id to your controller endpoint
function sendRequest(imageId) {
$.get('@Url.Action('SaveImageId')' + '?imageId=' + imageId, function(){
//show a loading gif maybe
});
}
//Your html
<div>
<img id="9" class="thumb" src="/Content/uploads/Jellyfish.jpg">
<input type='checkbox' class='sendImage' />
</div>
<div>
<img id="10" class="thumb" src="/Content/uploads/Lighthouse.jpg">
<input type='checkbox' class='sendImage' />
</div>
<div>
<img id="11" class="thumb" src="/Content/uploads/Chrysanthemum.jpg">
<input type='checkbox' class='sendImage' />
</div>
你可以分享你查看代码? – amhed 2013-03-18 00:47:44