1

I am trying to implement some save functionality via AJAX. I have a view with controls defined like below to be populated from the model:

@Html.LabelFor(model => model.mediaName, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.mediaName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.mediaName, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.mediaName, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.mediaName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.mediaName, "", new { @class = "text-danger" })

When a user modifies the data and clicks the save button, the View is able to build up the new data from those controls and send it to the Controller (which simply saves the model to the db).

I am trying to do the same but via AJAX but I am having problems accessing an "already-built" model from the controls...

function saveDetails() {
    var model = //HOW I GET THE MODEL?
    $.ajax({
        url: '/Media/SaveDetails',
        dataType: 'html',
        data: {
            obj: model
        },
        success: function (data) {

        }
    });
}

Is there any way I can access that model? Or I should build it control-by-control?

EDIT: This is how I expect the controller to get the action: (Medium is the entity used in the Model)

public ActionResult SaveDetails(DomainModel.Medium obj)
{
    db.Entry(obj).State = EntityState.Modified;
    db.SaveChanges();
    return PartialView("_MediaModalDetails", obj);
}
1
  • OKay So I assume....you want to hit the controller action SaveDetails...why not use an Ajax form... that submits the data by ajax & doesn't do any postback... putting the code in answers Commented Oct 15, 2017 at 9:33

2 Answers 2

2

Since the form works normally before adding the AJAX, presumably you have a <form> enclosing the input elements? If so, you can serialize that form. So, for example, let's say your form has id="myForm", then you can do something like this:

var model = $('#myForm').serialize();
Sign up to request clarification or add additional context in comments.

4 Comments

Would that be accepted as a Medium class in the controller? (just edited the question showing the controller action)
@byle.05: It should, because it's submitting the same form key/value pairs that a normal form post would. You might also try getting rid of that model variable and serializing directly to the data property: data: $('#myForm').serialize(), As long as the POST request matches, AJAX or otherwise, the model binder will be able to create the model. Examine the requests in your browser's development tools (specifically on the Network tab) and see if/how they differ.
Sorry for late reply... I tried this way and I was able to pass the values to the controller but the conversion was not possible. The controller is receiving a String with: "mediaName=Pulp+++++++++AA++++Fiction&idMediaType=MOVIE" but this doesn't look to be convertible to the model entity. Also loks query string format replacing the spaces by +. Maybe my form is wrongly defined? : <form id="frmModalDetails" method="post" class="modalWindowContent">
Solved with serializeArray(). Thanks!! :)
1
 @using (Ajax.BeginForm("SaveDetails", "Media", new AjaxOptions { HttpMethod = "POST", OnSuccess = "AfterEntry()", OnBegin="ValidateForm()"}, new { id = "myForm" })) 

It does the same thing which you will get my writing an external

$.ajax({
    url: '/Media/SaveDetails',  
    type: "POST",
   data: {obj: $('#myForm').serialize() },
   success: function (data) { AfterEntry(data) }
  }) 

// no need of dataType:'html' as its json

Using the Ajax.BeginForm technique will also do server side property validation for model.mediaName which you have mentioned in the Data Annotations

for e.g.

[Required(ErrorMessage = "Media Name is required")]
 public string mediaName{ get; set; }

Using ajax.BeginForm will show error with a message if mediaName is blank.. i.e. @Html.ValidationMessageFor will be fired

you will have to write extra long validation in jquery if you are trying to do the same but via external Ajax otherwise @Html.ValidationMessageFor won't be fired

1 Comment

Thanks for the answer Rohitas. Was mostly looking for how to send the data to the controller and the JSON 'form.serializeArray()' was the key. Thanks;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.