我尝试在用户汇总形式时将数据插入数据库,但仍然没有运气
我在浏览器中检查过控制台没有错误。
我逐步调试My JsonResult,我可以看到Model Contains数据和ModelState是真的,但是
当我调试我的JsonResult时,我可以看到Id Contains 0(也许Id为0导致问题?!)之后我看到这个我在我的控制器和我的Ajax中创建if / else语句,但仍然无法正常工作
我还在我的Json结果中的ViewBag.ID中存储了Id,而在View i中输入了隐藏的输入字段类型,并将ViewBag.ID存储为输入字段中的值。
有谁能请我指出正确的方向?!
控制器:
[HttpPost]
public JsonResult ProcessRequestRMA(RMA_History model)
{
ViewBag.ID = model.Id;
if (ModelState.IsValid)
{
if (ViewBag.ID == 0)
{
db.RMA_History.Add(new RMA_History
{
Id = ViewBag.ID,
Kundenavn = model.Kundenavn,
Ordrenummer = model.Ordrenummer
});
db.SaveChanges();
}
}
return Json(model, JsonRequestBehavior.AllowGet);
}
AJAX:
<form>
<input name="Ordrenummer" type="text" id="Ordrenummer" >
<input name="Kundenavn" type="text" id="Kundenavn" >
<input type="hidden" name="Id" id="Id" value="@ViewBag.ID" />
<button id="btn" type="submit">Send</button>
</form>
<script>
$(document).ready(function () {
$("#btn").click(function (e) {
e.preventDefault();
return myfunction();
});
function myfunction() {
var model = {
Kundenavn: $("#Kundenavn").val(),
Ordrenummer: $("#Ordrenummer").val(),
Id: $("#Id").val()
}
$.ajax({
type: 'POST',
url: "/Account/ProcessRequestRMA",
dataType: 'json',
data: {
Kundenavn: model.Kundenavn,
Ordrenummer: model.Ordrenummer,
Id: model.Id
},
beforeSend: function (status) {
if (model.Id == 0) {
status.Id = model.Id
status.Kundenavn = model.Kundenavn;
status.Ordrenummer = model.Ordrenummer;
console.log("Send");
}
else {
alert("Something Wrong");
}
},
success: function (run) {
if (run) {
console.log("Send success");
}
else {
alert("Something wrong in success");
}
},
error: function () {
console.log('something went wrong - debug it!');
}
});
}
});
</script>
型号:
public class RMA_History
{
public int Id { get; set; }
public string Kundenummer { get; set; }
public string Ordrenummer { get; set; }
//Table & Column Mappings
//Stuff here
//Key
HasKey(t => t.Id);
}
答案 0 :(得分:1)
if (ViewBag.ID == 0)
{
db.RMA_History.Add(new RMA_History
{
//here is your problem... typically you don't need to specify the id
//after you save changes, the id will come back to you and then you
//can store it in the viewbag
Id = ViewBag.ID,
//other stuff
}
}
您正在尝试使用ID为0保存记录。我假设在您的数据库中这是一个自动增量列。
尝试这样的事情:
var RMA = new RMA_History
{
Kundenavn = model.Kundenavn,
Ordrenummer = model.Ordrenummer
}
db.RMA_History.Add(RMA);
db.savechanges();
model.Id = RMA.Id;
return Json(model, JsonRequestBehavior.AllowGet);