byle.05
byle.05

Reputation: 196

Create and send whole model via AJAX in ASP.NET MVC

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);
}

Upvotes: 1

Views: 887

Answers (2)

Rohit Kumar
Rohit Kumar

Reputation: 1782

 @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

Upvotes: 1

David
David

Reputation: 218808

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();

Upvotes: 2

Related Questions