我有一个带有两个带有硬编码值的dropDown框的表单。我需要将用户从视图中选择的值传递给控制器并将其存储在数据库表中。
这是dropDown的HTML代码。
<div class="form-group">
<label for="UserType">User Type:</label>
<select name="usertype" class="form-control" id="drpUserType">
<option value="0">Please Select</option>
<option value="regular">Regular</option>
<option value="preLoader">Pre Loader</option>
</select>
</div>
这是脚本和AJAX。这会将值传递给控制器。
$("#btnSubmitCustomer").click(function (){
var customer = {};
customer.ID = $("#hdnCustomerID").val();
customer.UserType = $("#drpUserType").val();
$.ajax({
type: "POST",
data: {customer : customer},
dataType: "json",
url: "@Url.Action("Save", "Customer")",
success: function (response){
if(response.type == "Success"){
notifyMe("Customer Added Successfully", "Success");
clearForm();
setDataTable();
$('#customerModal').modal('hide');
}
},
error: function (error){
console.log(error)
$('#loading_spinner').hide();
}
});
});
这是控制器代码。
[HttpPost]
public JsonResult Save(Customer customer)
{
bool userType;
if (customer.UserType.Equals("preLoader"))
{
userType = customer.UserType == true;
}
else
{
userType = customer.UserType == false;
}
try
{
Customer cst = new Customer();
using (MyDBContext myDBContext = new MyDBContext())
{
if (customer != null)
{
DateTime localTime = DateTime.Now;
if (customer.ID == 0)
{
cst.UserType = userType;
myDBContext.Customer.Add(cst);
}
else
{
int customerID = customer.ID;
Customer customerOld = myDBContext.Customer.Where(x => x.ID == customerID).FirstOrDefault();
customerOld.UserType = customer.UserType;
}
myDBContext.SaveChanges();
}
}
return Json(new { type = "Success", data = cst });
}
catch (Exception ex)
{
string message = ex.Message;
if (ex.InnerException != null)
{
message += ex.InnerException.Message;
}
_Common.Log(message, "Customer", "save");
return Json(new { type = "Error", message = ex.Message });
}
}
在MySql表中,userType为tinyint(1)。我需要通过dropDown框验证usertype,如果“preLoader | true”则指定“1”,如果“regular | false”则指定“0”。但无论用户选择的选项是什么,我都会变得虚假。
我该如何解决?
答案 0 :(得分:0)
尝试在传递数据时使用此代码
var customer ={
ID = $("#hdnCustomerID").val();
UserType = $("#drpUserType").val();
};
在ajax:
$.ajax({
...
data: JSON.stringify({ customer: customer }),
...
});