简体   繁体   中英

Returning a view from a method by calling its method

I have a method in a controller named AspNetAssessment_QuestionController

public ActionResult Excel_Data(HttpPostedFileBase excelfile)
{
    if ( excelfile == null )
    {
        ViewBag.Error = "Please select an excel file";
        return View("Create");
    }
    else if (excelfile.FileName.EndsWith("xls") || excelfile.FileName.EndsWith("xlsx"))
    {
        return View("Index");
    }
    else
    {
        ViewBag.Error = "File type is incorrect";
        return View("Create");
    }        
}

Now when this method returns the view, the requested view needs some viewbag data to run its razor syntax, like in 'Create' and 'Index' both have:

@Html.DropDownList("ClassID", null, htmlAttributes: new { @class = "form-control" })

As the system just return my view without hitting the method it is not able to get value of viewbag from the method of Create and Index.

I also added the routes so they hit their method in routes.config file as

routes.MapRoute(
                name: "AspNetAssessment_Question/Create",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "AspNetAssessment_Question", action = "Create", id = UrlParameter.Optional }
            );

and same goes for index but when excel_data method return view I receive an error that Viewbag.propertyname data is missing on following url

http://localhost:1331/AspNetAssessment_Question/Excel_Data 

I even tried to call their methods like Create() instead of return view("Create") but it failed and didn't render the view.

The create method has two forms. One hits the method of Excel_data and other one call Create method

How can I hit their method and return the view from Excel_Data so that they get the viewbag data from their methods and from Excel_Data as well.

excel_data method assign viewbag.Error and in the method of create I have viewbag.ClassID and some more.

Solution for your problem is very simple

Before giving the solution , we need to understand two things view and redirecttoaction and its differences:

In short return view() is like a server.Transfer() in asp.net and whereas redirecttoaction will hit the 302 request to the browser.

Detailed info can be found in this very good article: http://www.dotnettricks.com/learn/mvc/return-view-vs-return-redirecttoaction-vs-return-redirect-vs-return-redirecttoroute

so now solution to your problem is:

Use to return redirectoaction() instead of return view()

your example slightly modified:

public ActionResult Excel_Data(HttpPostedFileBase excelfile)
        {
            if ( excelfile == null )
            {
                ViewBag.Error = "Please select an excel file";
                return View("Create");
            }else if (excelfile.FileName.EndsWith("xls") || excelfile.FileName.EndsWith("xlsx"))
            {
                return View("Index");
            }
            else
            {


        TempData["Error"] = "File type is incorrect";  //replaced tempdata with viewbag

                return RedirectToAction("Create","AspNetAssessment_QuestionController")
            }

        }

Note : For the error message to retain use tempdata["error"] instead of viewbag.error as mentioned in the above code.

And the data of the tempdata you can access directly in the create view like below without doing anything the create action method.

create view code ex:

@if(tempdata["error"]!= null)
{
    var result = tempdata["error"];
}

Thats it

FYI:

if you want an additional info like how to cast the different tempdata object and difference between the viewbag, viewdata , tempdata ,kindly refer this link: http://www.binaryintellect.net/articles/36941654-8bd4-4535-9226-ddf47841892f.aspx

That article had a very good explanation

Hope it be will helpful

Thanks Karthik

If it's only the error message that you want to display, you could save them to session/cookie and use RedirectToAction return RedirectToAction("Create", "AspNetAssessment_QuestionController"); instead of return View("Create"); .

Then in the Create/Index ActionResults, you could add something like this:

public ActionResult Create()
{
    ViewBag.Error = Session["ErrorMessage"].ToString();
    return View();
}

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