0

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.

Joe Higley
  • 1,250
  • 2
  • 12
  • 30
  • Possible duplicate of how to post form content via JQuery: https://stackoverflow.com/questions/1960240/jquery-ajax-submit-form – theoretical Nov 11 '17 at 04:15
  • Not really. My problem has to do with `@Html.EditorForModel` and you don't really get to give you form an id in that case. – Joe Higley Nov 11 '17 at 09:14

1 Answers1

1

The EditorForModel helper method renders input element for each property in your model. But your attempt was to pass the serialized version of model passed to the view , which does not makes sense because that C# line will be executed when razor renders the page and it will not have the values user entered.

If you want to make an ajax call with the input form elements to server, you need to read the value of each one of them and build a js object matching to the structure of your Item class and use that to make your ajax call. But there is an easy way to do this. You can simply keep your input elements inside a form and use jQuery serialize method to generate the serialized version of your string and send that.

@model Item
<form asp-action="Create" id="create-form" method="post">
    @Html.EditorForModel()
    <button type="submit" id="btn-save">Submit</button>
</form>
<div id="form-container"></div>

This will render input elements for each property in the Item class, inside the form along with the submit button.

Now wire up the submit event on this form, and serialize the form and use that for the ajax call.

$(function() {
    $("#create-form").submit(function (e) {
        var $form = $(this);
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: $form.attr("action"),
            data: $form.serialize()
        }).done(function(data) {
            $('#form-container').html(data);
        });
    });
})

Personally i would not use the EditorFor with any entity classes created by EF. You should consider using view models which has only properties needed for the specific view. Even with that, It is rare that i use EditorForModel unless it is a tiny view model ( I like writing markup for my input elements where i have full control on how the markup should be )

Shyju
  • 197,032
  • 96
  • 389
  • 477
  • This helped a lot. However giving the form an action caused it to skip the js and go straight to the action. I fixed that by passing the `@Url.Action()` to my js function along with the form id with the `onclick` method of the button. If you could edit your answer to reflect that, it would be much appreciated @Shyju. I am marking this as the answer tho – Joe Higley Nov 11 '17 at 17:59
  • The `e.preventDefault();` part should prevent the normal form submit. Remove on the `onclick` and use the unobtrusive way i used – Shyju Nov 11 '17 at 18:04
  • interesting cause it wasn't. I know it's supposed to, so I'm not sure why it wasn't working in my case. Anyway I've marked this as the answer. – Joe Higley Nov 11 '17 at 18:06