Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.net MVC Controller will not return view

Tags:

c#

asp.net-mvc

Still kinda new to ASP.net and I have this strange problem. Its a very basic scenario but something is up and I can't figure it out. Deploy should return a view named Deploy that is typed to the model CompiledAppModel. However, when you click install in the view it never leaves the page despite calling the return View() method. Any ideas?

Here is my controller:

[HttpPost]
public ActionResult Deploy(string key_name, string custom_folder = "")
{
    string userId = Membership.GetUser().ProviderUserKey.ToString();
    UserDataModel user_info = _user_data_service.getUserDataByPrimaryIDNoDB(userId, HttpContext.Cache);
    log.Trace("Deploy was called. key_name:" + key_name + " UID: " + user_info.UID);

    // first we'll call the info to install remote application
    bool serviceInstall = _fms_app_service.DeployFmsApp(user_info, key_name, custom_folder);

    // then we'll call to generate client side info
    bool clientInstall = _fms_app_service.CompileClientApp(user_info, key_name);

    var model = _fms_app_service.getInstalledAppInfo(user_info, key_name);
    if (serviceInstall && clientInstall)
    {
        return RedirectToAction("Deploy", model);
    }

    return View("Error");
}

and my view:

@model IEnumerable<Models.Applications.FmsAppModel>

@foreach (var item in Model) {
    <div class="col">
        <h2>@Html.DisplayFor(modelItem => item.friendly_name)</h2>
        <p>@Html.DisplayFor(modelItem => item.app_description)</p>
        <p><strong>Tags:</strong> @Html.DisplayFor(modelItem => item.app_type)</p>

        <a href="#" class="btn btn-primary install-app" data-key-name="@(item.key_name)">Install</a>

        @Html.ActionLink("Details", "Detailss", new {  id=item.app_id  })
    </div>
}
</div>

<script type="text/javascript">
   (function () {
        $('.install-app').on('click', function (e) {
            e.preventDefault();
            var data_key_name = $(this).data('key-name');
            //ajax install app
            $.ajax({
                type: "POST",
                url: '@Url.Action("Deploy")',
                data: {
                    key_name: data_key_name
                }
            });
        });
    })();
</script>

And the model.

public class CompiledAppModel
{
    [Display(Name = "Admin URL")]
    public string adminURL { get; set; }

    [Display(Name = "Viewer URL")]
    public string viewerURL { get; set; }

    [Display(Name = "Embed URL")]
    public string embedURL { get; set; }
}
like image 903
user1608132 Avatar asked Oct 16 '12 02:10

user1608132


People also ask

How to create a view in MVC 5 controller-empty?

Select "MVC 5 Controller - Empty" to add an empty controller. Click on the "Add" button. Now we need to create a view. Right-click on "Index" and select "Add View...". Change the view name from "Index" to your desired name. By default it considers an action method name as the view name. Select "Empty (without model)" as the template.

How to return a viewname from a controller in MVC?

This article describes returning a viewname from a controller. Create a MVC project from the "Empty" template. Right-click on "Controllers" and select "Add" >> "Controller...". Select "MVC 5 Controller - Empty" to add an empty controller. Click on the "Add" button. Now we need to create a view.

What is emptyresult in ASP NET MVC?

There is nothing like a VOID ActionResult (Action Method), hence ASP.Net MVC has created a class EmptyResult whose object is returned in case when NULL value or Nothing needs to be returned from Controller to View in ASP.Net MVC Razor.

How does the controller work with Ajax forms?

The Controller consists of two Action methods. Inside this Action method, simply the View is returned. This Action method handles the AJAX Form submission and it accepts the value of the Form elements as parameter.


2 Answers

I assume that you really want to redirect after making the ajax call.

As far as i know, you have to implement a custom ActionResult, something like:

public class AjaxAwareRedirectResult : RedirectResult
{       
    public AjaxAwareRedirectResult(String url)
        : base(url)
    {
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if ( context.RequestContext.HttpContext.Request.IsAjaxRequest() )
        {
            String destinationUrl = UrlHelper.GenerateContentUrl(Url, context.HttpContext);

            JavaScriptResult result = new JavaScriptResult()
            {
                Script = "window.location='" + destinationUrl + "';"
            };
            result.ExecuteResult(context);
        }
        else
        {
            base.ExecuteResult(context);
        }
    }
}

In your controller, just do:

    [HttpPost]
public ActionResult Deploy(string key_name, string custom_folder = "")
{
    string userId = Membership.GetUser().ProviderUserKey.ToString();
    UserDataModel user_info = _user_data_service.getUserDataByPrimaryIDNoDB(userId, HttpContext.Cache);
    log.Trace("Deploy was called. key_name:" + key_name + " UID: " + user_info.UID);
    // first we'll call the info to install remote application
    bool serviceInstall = _fms_app_service.DeployFmsApp(user_info, key_name, custom_folder);
    // then we'll call to generate client side info
    bool clientInstall = _fms_app_service.CompileClientApp(user_info, key_name);

    var model = _fms_app_service.getInstalledAppInfo(user_info, key_name);
    if (serviceInstall && clientInstall)
    {
        return RedirectToAction("Deploy", model);
    }
    return AjaxAwareRedirectResult("/foo");
}

But, as I said, this is just me assuming that you really want to redirect after the ajax call.

like image 65
b_meyer Avatar answered Oct 05 '22 23:10

b_meyer


Looks to me like your using an Ajax call to do your post back to the server, in which case the result isn't going to get rendered to the page without a little extra work. You can define a success handler on the ajax call to take action when the ajax call returns. So something like

<script type="text/javascript"> (function () {
    $('.install-app').on('click', function (e) {
        e.preventDefault();
        var data_key_name = $(this).data('key-name');
        //ajax install app
        $.ajax({
            type: "POST",
            url: '@Url.Action("Deploy")',
            data: {
                key_name: data_key_name
            },
            success: function(data) { alert(data) }
        });
    });
})();

will give you an alert message with the HTML returned from the ajax call when the request completes.

I'd also use Firebug or the developer tools in Chrome to view the HTML returned, if there is an exception occurring on the server you should be able to inspect this in more detail using these tools.

like image 23
Neil F Avatar answered Oct 05 '22 22:10

Neil F