Oflocet Oflocet - 3 months ago 20
C# Question

Call a method without loading a view in MVC

I am currently trying to call a method from my view to change a boolean in my database, the only thing i don't know since i am not really familiar with MVC is that whenever i call my controller method it gives me a blank page. I just want to call the method but stay in the actual view.

Here is the part of code in my view.

<td><a href="@Url.Action("PutInBin", "Capture", new { captureId = @Model.Files.Captures.ElementAt(i).Capture_Id })", onclick="DeleteCapture(@(i + 1))">Delete</a></td>


And here is the method in my controller

public void PutInBin(int captureId)
{
QueryCaptureToBin queryCaptureToBin = new QueryCaptureToBin();
queryCaptureToBin.Capture_Id = captureId;
client.PlaceCaptureInBin(queryCaptureToBin, userParams);
}

Answer

You could use AJAX:

<td>
    @Ajax.ActionLink(
        "Delete",
        "PutInBin", 
        "Capture", 
        new { 
            captureId = Model.Files.Captures.ElementAt(i).Capture_Id 
        },
        new AjaxOptions {
            HttpMethod = "POST",
        }  
    )       
</td>

and don't forget to include the jquery.unobtrusive-ajax.js script to your page:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

and your controller action:

[HttpPost]
public ActionResult PutInBin(int captureId)
{
    QueryCaptureToBin queryCaptureToBin = new QueryCaptureToBin();
    queryCaptureToBin.Capture_Id = captureId;
    client.PlaceCaptureInBin(queryCaptureToBin, userParams);
    return new EmptyResult();
}

and if you wanted to get notification when the delete finishes:

<td>
    @Ajax.ActionLink(
        "Delete",
        "PutInBin", 
        "Capture", 
        new { 
            captureId = Model.Files.Captures.ElementAt(i).Capture_Id 
        },
        new AjaxOptions {
            HttpMethod = "POST",
            OnSuccess = "onDeleteSuccess"
        }
    )       
</td>

and then you would have your onDeleteSuccess javascript function:

var onDeleteSuccess = function(result) {
    // normally the result variable will contain the response
    // from the server but in this case since we returned an EmptyResult
    // don't expect to find anything useful in it.

    alert('The capture was successfully deleted');
};
Comments