我试图将一个对象传递给IActionResult并列出这些对象,我正在使用AJAX(Jquery),但是当我开始调试该对象时,控制器中便带有空值。
我尝试更改ajax代码的结构,但是我对此确实很陌生。
这是我的控制者,一位联系人
//模型
public class Contact
{
public string firstName { get; set; }
public string lastName { get; set; }
public string phone { get; set; }
public string company { get; set; }
public string email { get; set; }
}
// HomeController
public JsonResult addContact(Contact _contact)
{
bool isThere = false;
foreach(Contact c in this.contacts){
if( c.phone == _contact.phone ){
isThere = true;
}
}
if(!isThere){
this.contacts.Add(_contact);
return Json(new { msg = "ok" });
}
else{
return Json(new { msg = "exists" });
}
}
这是我的.js
function addContact() {
$('#addUserModal').modal("hide");
var _firstName = $('#firstName').val();
var _lastName = $('#lastName').val();
var _email = $('#email').val();
var _phone = $('#phone').val();
var _company = $('#company').val();
//let's create a objet just like our user.cs
var Contact = {
firstName: _firstName,
lastName: _lastName,
email: _email,
phone: _phone,
company: _company
};
console.log(Contact);
$.ajax({
type: "POST",
dataType: "JSON",
contentType: 'application/json; charset=utg-8',
url: "/Home/addContact",
data: JSON.stringify({
'_contact': Contact
}),
error: function () {
toastr.error('system Error, check your connection or re-debug your code', 'Error', {
timeOut: 6000,
positionClass: 'toast-top-full-width'
});
},
success: function (data) {
if (data.msg === "ok") {
toastr.success('OK, Contact added', 'ok', {
timeOut: 6000,
positionClass: 'toast-top-full-width'
});
$("#addContactModal").modal("hide"); //to hide my idModal
$("#listContactTableId").load("/Home/getContacts");
}
else if (data.msg === "exists") {
toastr.error("You're trying to add a user that alreday exists", "Eye!", {
timeOut: 6000,
positionClass: 'toast-top-full-width'
});
}
}
});
}
答案 0 :(得分:0)
``
[HttpPost]public string addContact(Contact obj){ return "Success";}
这里,名字和姓氏应该是模型中的属性。 公共字符串MyName ....等请尝试@viviramji
$("#btn").on("click",function(){
var a= $("#IDforName").val();
var b=$("idLatname").val();
$.ajax({
type:"post",
url: "@Url.Action("addContact","YourControllerName")",
data:
{
firstname:a,
lastname:b
},
success: function()
{
alert("success!");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="IDforName" placeholder="Enter Name" name="firstname"/>
<input type="text" id="idLatname" placeholder="Enter lastname" name="lastname"/>
<input type="button" id="btn" value="submit"/>
答案 1 :(得分:0)
您的模型只需要对象而不是包装器,就可以更改
data: JSON.stringify({
'_contact': Contact
})
到
data: JSON.stringify(Contact)