N.Max
N.Max

Reputation: 1

Link HTML site with MVC site's Action

I'm building a HTML page on button click, it will transfer data from localStorage at HTML page to MVC site's action and process action then save data at MVC site

this is my HTML button 's function:

function OH10() {            
            var url1 = "@Url.Action('createFuel','FuelExtras')";
            debugger;
            for (var i = 0; i < localStorage.length; i++) {
                var key = localStorage.key(i);
                var val = localStorage.getItem(key);
                $.ajax({
                    type: "POST",
                    url: url1,
                    data: val,
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function () {
                        alert("Data has been added successfully.");
                    },
                    error: function () {
                        alert("Error while inserting data");
                    }
                });
            }
};

And MVC site 's action:

[HttpPost]
        [System.Web.Services.WebMethod]
        public ActionResult createFuel(FuelExtra fuelExtra)
        {
            db.FuelExtras.Add(fuelExtra);
            db.SaveChanges();
            string message = "SUCCESS";
            return Json(new { Message = message, JsonRequestBehavior.AllowGet });
        }

Any Suggestions guys? And 1 more question is right now in development, I've build 2 sites in same Solution, but when I deploy it to intranet i have to separate it into 2 sites. Is it ok?

Upvotes: 0

Views: 77

Answers (1)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

I found several mistakes in your example:

1) System.Web.Services.WebMethod only used in webforms, it cannot be used for ActionResult in MVC and should be removed.

2) The AJAX callback placed inside a loop, therefore it will execute multiple times instead of single request.

3) The passed data is the last localStorage value taken from getItem() function as single string, not a key-value pair reflecting model property names and their values.

Hence, by assuming you have this model:

public class FuelExtra
{
    public string CaptainEmpNo { get; set; } 
    public string AirCraft { get; set; } 
    public string FlightNo { get; set; } 
    public string DepartureAirport { get; set; } 
    public string ArrivalAirport { get; set; }

    // other properties
}

Then you should send key-value pair object as JSON string because the contentType setting has been set to application/json by JSON.stringify(), as in example below:

function OH10() {            
    var key = []; // array of keys
    var val = []; // array of values

    var obj = {}; // combined KVP object

    var url1 = "@Url.Action("CreateFuel", "FuelExtras")";
    debugger;
    for (var i = 0; i < localStorage.length; i++) {
        key.push(localStorage.key(i));
        val.push(localStorage.getItem(key));
    }

    for (var n = 0; n < key.length; n++) {
        obj[key[n]] = val[n]; // create KVP object from both arrays
    }

    $.ajax({
       type: "POST",
       url: url1,
       data: JSON.stringify({ fuelExtra: obj }), // convert KVP object to JSON string
       dataType: "json",
       contentType: "application/json; charset=utf-8",
       success: function (result) {
           alert("Data has been added successfully.");
       },
       error: function (xhr, status, err) {
           alert("Error while inserting data");
       }
    });
};

And the controller action should be like this:

[HttpPost]
public ActionResult CreateFuel(FuelExtra fuelExtra)
{
    db.FuelExtras.Add(fuelExtra);
    db.SaveChanges();
    return Json(new { Message = "SUCCESS" });
}

Since you're sending AJAX request as POST method, then JsonRequestBehavior.AllowGet is unnecessary.

Note:

Make sure all key names inside passed JSON string from AJAX is the same as all property names declared inside FuelExtra class.

Upvotes: 1

Related Questions