我正在使用ajax和jquery在数据库中插入数据。当我单击保存按钮,然后JSON函数不调用控制器。我也使用了debug和JSON数据返回
{"Qt_ID":2,"EnteryDate":"11/10/2018","Purpose":"test","Quot":[{"Srno":"1","PartyName":"Brisk","file":"C:\\fakepath\\aaa.png","IsMature":"true"}],"AddNew":"New"}
,但不传递给控制器。有人告诉我我哪里错了,我的代码有什么问题。我尝试了很多,但是我不明白问题是什么。任何专家都请检查我的代码并告诉我我错了。
C#
public ActionResult mQuotationInsert(int Qt_ID, string EnteryDate, string Purpose, Quotation[] Quot, string AddNew, HttpPostedFileBase file)
{
string result = "Error! Order Is Not Complete!";
try
{
objQuotation.QuotationInsert(Qt_ID, EnteryDate, Purpose, Quot, AddNew, file);
ModelState.Clear();
result = "Quotation Inserted Successfully!";
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
throw;
}
}
public int QuotationInsert(int Qt_ID, string EnteryDate, string Purpose, Quotation[] Quot, string AddNew, HttpPostedFileBase file)
{
try
{
con.Open();
tr = con.BeginTransaction();
if (AddNew == "New")
{
cmd = new SqlCommand("Select Right('00' + Cast(ISNULL(MAX(Qt_ID),0)+1 as varchar(2)) + '', 2) from QuotationMain", con);
cmd.Transaction = tr;
Qt_ID = Convert.ToInt32(cmd.ExecuteScalar().ToString());
cmd = new SqlCommand("Sp_QuotationMainInsert", con);
}
else
cmd = new SqlCommand("Sp_QuotationMainUpdate", con);
cmd.Parameters.AddWithValue("@Qt_ID", Qt_ID);
cmd.Parameters.AddWithValue("@Comp_ID", 1);
if (EnteryDate != null)
cmd.Parameters.AddWithValue("@EnteryDate", EnteryDate);
else
cmd.Parameters.AddWithValue("@EnteryDate", string.Empty);
cmd.Parameters.AddWithValue("@Username", HttpContext.Current.Session["AgentName"]);
cmd.Parameters.AddWithValue("@Purpose", Purpose);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Transaction = tr;
cmd.ExecuteNonQuery();
if(Quot !=null)
{
for (int i = 0; i < Quot.Length; i++)
{
try
{
string ImageName = System.IO.Path.GetFileName(file.FileName);
string physicalPath = HttpContext.Current.Server.MapPath("~/Images/" + ImageName);
file.SaveAs(physicalPath);
if (AddNew == "New")
{
cmd = new SqlCommand("Select ISNULL(MAX(Qt_Dt_ID), 0) + 1 from QuotationDetail", con);
cmd.Transaction = tr;
mQt_Det_ID = Convert.ToInt32(cmd.ExecuteScalar());
cmd = new SqlCommand("Sp_QuotationDetailInsert", con);
cmd.Parameters.AddWithValue("@Qt_Dt_ID", mQt_Det_ID);
}
else if (AddNew == "Edit")
{
cmd = new SqlCommand("Sp_QuotationDetailUpdate", con);
cmd.Parameters.AddWithValue("@Qt_Dt_ID", Quot[i].Qt_Dt_ID);
}
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Qt_Dt_ID", mQt_Det_ID);
cmd.Parameters.AddWithValue("@Qt_ID", Qt_ID);
cmd.Parameters.AddWithValue("@SrNo", Quot[i].Srno);
cmd.Parameters.AddWithValue("@PartyName", Quot[i].PartyName);
cmd.Parameters.AddWithValue("@IsMature",Quot[i].IsMature);
if (file != null)
cmd.Parameters.AddWithValue("@Image", ImageName);
cmd.Transaction = tr;
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
}
}
tr.Commit();
return i;
}
catch (SqlException sqlex)
{
tr.Rollback();
throw sqlex; // read all sql error
}
catch (Exception ex)
{
tr.Rollback();
throw ex; // General execption
}
finally
{
con.Close();
}
jquery
function saveQuotation(data) {
if ($.trim($("#Qt_ID").val()) == "" || $.trim($("#txtNEnteryDate").val()) == "" || $.trim($("#txtNPurpose").val()) == "") return;
return $.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: "/Home/mQuotationInsert",
data: data,
success: function (result) {
alert(result);
location.reload();
},
error: function () {
alert("Error!")
}
});
}
//Collect Multiple Order List For Pass To Controller
$("#saveQuotation").click(function (e)
{
e.preventDefault();
var QuotationArr = [];
QuotationArr.length = 0;
$.each($("#detailsTable tbody tr"), function () {
QuotationArr.push({
Srno: $(this).find('td:eq(0)').html(),
PartyName: $(this).find('td:eq(1)').html(),
file: $(this).find('td:eq(2)').html(),
IsMature: $(this).find('td:eq(3)').html()
});
});
var data = JSON.stringify({
Qt_ID: parseInt($("#Qt_ID").val()),
EnteryDate: $("#txtNEnteryDate").val(),
Purpose: $("#txtNPurpose").val(),
Quot: QuotationArr,
AddNew: $("#AddNew").val()
});
$.when(saveQuotation(data)).then(function (response) {
console.log(response);
}).fail(function (err) {
console.log(err);
});
});
HTML
<div class="modal fade" id="centralModalLGInfoDemo" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-lg modal-notify modal-info" role="document">
<!--Content-->
<div class="modal-content" style="width:140%">
<!--Header-->
<div class="modal-header">
<p class="heading lead">Add New Quotation</p>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true" class="white-text">×</span>
</button>
</div>
<!--Body-->
<form id="NewQuotationForm">
<div class="modal-body">
<div class="form-row">
<div class="col" id="Qt_ID">
<div class="md-form">
@Html.TextBox("Qt_ID", (string)ViewBag.QuotationMaxNo, new { @class = "form-control mr-sm-2 w-5", @id = "Qt_ID", @readonly=true, Required = true })
</div>
</div>
<div class="col">
<div class="md-form mr-4">
@Html.TextBoxFor(m => m.EnteryDate, new { @class = "form-control", @id = "txtNEnteryDate", Required = true })
<label for="lblEntryDate">Entry Date</label>
</div>
</div>
<div class="col">
<div class="md-form">
@Html.TextBoxFor(m => m.Purpose, new { @class = "form-control", @id = "txtNPurpose", Required = true })
<label for="lblPurpose">Purpose</label>
</div>
</div>
</div>
<!--Detail-->
<h5 style="margin-top:10px;color:#ff6347">Quotation Details</h5>
<hr />
<div>
<div class="form-row">
<div class="col">
<div class="md-form">
<label for="lblPartyName">Party Name</label>
<input type="text" id="PartyName" name="PartyName" placeholder="Party Name" class="form-control" ,Required=true />
</div>
</div>
<div class="col">
<form class="md-form">
<label for="lblPartyName">Image File</label>
<div class="file-field">
<div class="btn btn-outline-success btn-sm float-left">
<input type="file" id="file" name="file">
</div>
<div class="file-path-wrapper" hidden>
<input class="file-path validate" type="text" placeholder="Upload your file">
</div>
</div>
</form>
</div>
<div class="col">
<!-- IsMature-->
<div class="custom-control custom-checkbox custom-control-inline">
@Html.CheckBoxFor(m => m.IsMature, new { @class = "custom-control-input", @id = "chkNIsMature" })
<label class="custom-control-label" for="chkNIsMature">Mature</label>
</div>
</div>
<div class="col-md-2 col-lg-offset-4">
<a id="addToList" class="btn btn-primary">Add To List</a>
</div>
</div>
<table id="detailsTable" class="table">
<thead style="background-color:#007bff; color:white">
<tr>
<th style="width:2%">SrNo.</th>
<th style="width:40%">Party Name</th>
<th style="width:30%">Image</th>
<th style="width:30%">Mature</th>
<th style="width:10%"></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-primary" data-dismiss="modal">Close</button>
<button id="saveQuotation" type="submit" class="btn btn-primary">Save Record</button>
</div>
</div>
</form>
</div>
<!--/.Content-->
</div>
</div>
答案 0 :(得分:2)
首先,在服务器端创建一个模型
public class DataModel
{
public int Qt_ID { get; set; }
public string EnteryDate { get; set; }
public string Purpose { get; set; }
public Quotation[] Quot { get; set; }
public string AddNew { get; set; }
}
public class Quotation
{
public int Qt_Dt_ID { get; set; }
public int Srno { get; set; }
public string PartyName { get; set; }
public bool IsMature { get; set; }
}
最好使用一些验证。
然后使用DataModel类而不是单独传递每个属性
using Microsoft.AspNetCore.Mvc;
[HttpPost]
public ActionResult mQuotationInsert([FromBody] DataModel model)
{
// do the rest
}
请注意属性[HttpPost]
和[FromBody]
。这两个有助于数据正确绑定。
您有两个选择。
对于数字2,take a look here
其余的代码也没问题。
答案 1 :(得分:0)
尝试使用控制器方法上方的[HttpPost]属性