Im trying insert data into database when user sumbit form , but still no luck
I checked Console in Browser there is no error.
i debugged step by step My JsonResult and i can see Model Contains data and ModelState its true , but
When i debug my JsonResult, I can see Id Contains 0 (maybe Id is 0 cause the problem?!) and after i saw this i make if/else statement both in my Controller and in my Ajax , but still not working.
I also stored Id in a ViewBag.ID in my Json Result and than in View i make input field type hidden and stored the ViewBag.ID as value in input field.
Can anyone please point me in the right direction?!
Controller:
[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>
Model:
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);
}