I'm trying to use Ajax to pass my form data for creating a database object to the create action. I am doing this because I want to update a partial when it is successful. I cannot however seem to retrieve the data from the form.
I have tried passing the model thru the url like so but it turns up empty:
<button type="submit" onclick="javascript: CreateEntity('@Url.Action("CreateItem", "Home", Model)')">Submit</button>
<script>
function CreateEntity(createAction) {
$.ajax({
type: "POST",
url: createAction,
dataType: 'html',
success: function (data) {
$('#form-container).html(data);
}
});
}
</script>
I have also tried passing the model into ajax as a json string but I get a weird incorrect syntax error:
<button type="submit" onclick="javascript: CreateEntity('@Url.Action("CreateItem", "Home")', '@Html.Raw(Json.Serialize(Model))')">Submit</button>
<script>
function CreateEntity(createAction, entity) {
var model = JSON.parse(entity);
$.ajax({
type: "POST",
url: createAction,
data: { model: model },
dataType: 'html',
success: function (data) {
$('#form-container).html(data);
}
});
}
</script>
My Create action looks basically like this:
public IActionResult (Item model)
{
//save model to db
}
But all of the models fields come back as 0 or null no matter what I entered in the form.
Edit:
The Form is being generated by EntityFramework like so:
@Html.EditorForModel()
I need to be able to take the input from this and pass it thru ajax.