简体   繁体   中英

MVC controller doesn't run on view load

I am brand new to ASP.NET MVC and I'm really confused. I have a controller ActionResult Method that assigns values to different items from my viewmodel. I've done a lot of searching but I just can't figure it out. How do you get the controller to run when the view loads, and then take a value from the method and use it in your view? In my view I have a span and I want the value of StatusVM.StatusName from the controller method to display in a label in the view.

Here is my view:

@model Models.StatusViewModel

@using (Html.BeginForm())
{    
    <span>@Html.LabelFor(m => m.StatusName)</span>
}

Here is my controller:

public ActionResult Status()
{
    var Statuses = _Methods.GetStatuses();

    var AccountInfo = _Methods.GetAccount(User.AccountID) ?? new TC.DomainModels.Models.AccountModel();

    var StatusVM = new StatusViewModel();            

    //fill out the VM, you can use Mappers, you can use switch, anything to get the values form the account and tracStatusList into the VM

    var accountStatusInfo = Statuses.Where(s => s.StatusId == (int)AccountInfo.Status).FirstOrDefault();

    StatusVM.StatusName = String.IsNullOrEmpty(accountStatusInfo.StatusMask) ? accountStatusInfo.Status : accountStatusInfo.StatusMask;

    var carrierTerm = _accountService.GetAccountCarrierTerms(User.AccountID);
    if(carrierTerm.IsSMSNE)
    {
        StatusVM.ImagePath = accountStatusInfo.SmsneImage; 
    }                
    else
    {
         StatusVM.ImagePath = accountStatusInfo.StatusImage; 
    }


    switch (AccountInfo.Status)
    {
        case TC.DomainModels.Models.Status.Certified :
            StatusVM.ModalPath = "";
            break;
    }

    return PartialView("Navbar/nav_carrierstatus_new", StatusVM);
}

and here is my viewmodel:

public class StatusViewModel
{
    public string StatusName { get; set; }
    public string ImagePath { get; set; }
    public bool UseImage { get { return !String.IsNullOrEmpty(ImagePath); } }
    public string ModalPath { get; set; }

    public StatusViewModel()
    {

    }
}

If anyone can tell me what I'm doing wrong that would be great. Thanks in advance.

Updated Error Message:

{"Execution of the child request failed. Please examine the InnerException for more information."}

{"The controller for path '/' was not found or does not implement IController."}

StackTrace:

   at System.Web.Mvc.HttpHandlerUtil.ServerExecuteHttpHandlerWrapper.Wrap[TResult](Func`1 func)
   at System.Web.Mvc.HttpHandlerUtil.ServerExecuteHttpHandlerAsyncWrapper.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
   at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride)
   at System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage)
   at System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm)
   at System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm)
   at System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter)
   at System.Web.Mvc.Html.ChildActionExtensions.Action(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues)
   at System.Web.Mvc.Html.ChildActionExtensions.Action(HtmlHelper htmlHelper, String actionName, String controllerName)
   at ASP._Page_Views_Shared_Navbar__navbar_cshtml.Execute() in c:\source code\TC Web UI Project\Branches\Branch Update TF Status Process\Views\Shared\Navbar\_navbar.cshtml:line 20
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
   at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
   at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
   at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
   at System.Web.Mvc.HtmlHelper.RenderPartialInternal(String partialViewName, ViewDataDictionary viewData, Object model, TextWriter writer, ViewEngineCollection viewEngineCollection)
   at System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName, Object model, ViewDataDictionary viewData)
   at System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName)
   at ASP._Page_Views_Shared_std_siteheader_partialview_cshtml.Execute() in c:\source code\TC Web UI Project\Branches\Branch Update TF Status Process\\Views\Shared\std_siteheader_partialview.cshtml:line 7
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
   at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
   at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
   at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
   at System.Web.Mvc.HtmlHelper.RenderPartialInternal(String partialViewName, ViewDataDictionary viewData, Object model, TextWriter writer, ViewEngineCollection viewEngineCollection)
   at System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName, Object model, ViewDataDictionary viewData)
   at System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName)
   at ASP._Page_Views_Shared__Layout_cshtml.Execute() in c:\source code\TC Web UI Project\Branches\Branch Update TF Status Process\Views\Shared\_Layout.cshtml:line 33
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
   at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer)
   at System.Web.WebPages.WebPageBase.<>c__DisplayClass3.<RenderPageCore>b__2(TextWriter writer)
   at System.Web.WebPages.HelperResult.WriteTo(TextWriter writer)
   at System.Web.WebPages.WebPageExecutingBase.WriteTo(TextWriter writer, HelperResult content)
   at System.Web.WebPages.WebPageBase.Write(HelperResult result)
   at System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body)
   at System.Web.WebPages.WebPageBase.PopContext()
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
   at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
   at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
   at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)

View that calls partial view:

<nav class="navbar navbar-default">
    <div id="AccountInfoBar" class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#top-nav">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            @Html.Partial("Navbar/nav_branding_icons")
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="top-nav">
            <ul class="nav navbar-nav">
                <li id="acctswitch_navsection">@Html.Partial("Navbar/nav_account_switching", new List<Tcetra.Models.AccountSwitchViewModelList>())</li>
                <li id="account_navsection">@Html.Partial("Navbar/nav_account_info")</li>\
                <li id="carriersts_navsection">@Html.Action("Status", "Navbar")</li>
            </ul>

            <ul class="nav navbar-nav navbar-right">
                @Html.Partial("Navbar/nav_recent_transactions")
                @Html.Partial("Navbar/nav_cart")
                <li id="signout"><a href="@Url.Action("Logout", "Login", new { area = "" })" class="HeaderSignOutLink">Sign Out</a></li>
            </ul>
        </div><!-- /.navbar-collapse -->
    </div><!-- /.container-fluid -->
</nav>

I think I know what you are looking for. From the comments to this question:

Patrick said:

What URL are you using to access this?

hollyquinn responded:

@Patrick it loads inside of another page. I'm getting it from <li id="carriersts_navsection">@Html.Partial("Navbar/TStatus")</li>

The @Html.Partial method renders a partial during the execution of the current controller action. It does not invoke another controller action -- and I think this is where your disconnect lies.

Instead, it looks like you want to invoke another controller action while rendering the view for the current controller action:

<li id="carriersts_navsection">@Html.Action("Status", "Navbar")</li>

You want @Html.Action (ChildActionExtensions.Action)

Invokes the specified child action method using the specified parameters and controller name and returns the result as an HTML string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM