我有一张表格:
<div class="modal-body">
<form class="form-horizontal well">
<div class="form-group">
<label for="txtSubCategoryName" class="col-lg-4 control-label">Sub Category Name:</label>
<div class="col-lg-8">
<input type="text" class="txtSubCategoryName form-control" placeholder="The description of the Sub Category" />
</div>
</div>
<div class="form-group">
<label for="cmbCostCentre" class="col-lg-4 control-label">Default Cost Centre:</label>
<div class="col-lg-8">
<select class="form-control cmbCostCentre">
<option value="0">None</option>
<option value="1">Craig</option>
<option value="2">Melanie</option>
</select>
</div>
</div>
</form>
<div class="modal-footer">
<button class="btn btn-primary btnSubmitNewSubcategory">Save</button>
<a class="btn btn-info" data-dismiss="modal">Cancel</a>
</div>
</div>
在click事件中,我使用一些javascript向我的MVC应用程序发送JSON调用。
<script type="text/javascript">
$(document).ready(function () {
$('.btnSubmitNewSubcategory').click(function () {
var data = { description: $('.txtSubCategoryName').val(), defaultcostcentre: $('.cmbCostCentre'), categoryid: $('.Id').val() };
$.ajax({
url: '/Category/SaveSubCategory',
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
cache: false,
async: true,
success: function (result) {
if (result.Success == 'true') {
window.location = '/Category/EditCategory?categoryId=13';
} else {
alert(result.Message);
}
},
error: function () {
alert("Oh no...");
}
});
});
});
</script>
但是,当我的MVC应用程序中的事件被触发时,将填充值,除非cmbCostCentre,它总是为NULL,即使我选择了一个项目。
你能明白为什么吗?
答案 0 :(得分:1)
您正在$('.cmbCostCentre')
中传递jQuery对象defaultcostcentre
。
使用
var data = {
description: $('.txtSubCategoryName').val(),
defaultcostcentre: $('.cmbCostCentre').val(), // Here you have missed .val()
categoryid: $('.Id').val()
};
答案 1 :(得分:0)
你必须在select元素上调用val(),否则它不会返回任何值..
所以,而不是
var data = { description: $('.txtSubCategoryName').val(), defaultcostcentre: *$('.cmbCostCentre')*, categoryid: $('.Id').val() };
你应该把它写成
var data = { description: $('.txtSubCategoryName').val(), defaultcostcentre: *$('.cmbCostCentre').val()*, categoryid: $('.Id').val() };