Home > database >  ASP.NET MVC - How to return post request results to the View?
ASP.NET MVC - How to return post request results to the View?

Time:11-20

I have a controller class with the ActionResult of a post request.

public ActionResult Test()
{
    return View()
}

[HttpPost]
public ActionResult Test()
{
    Service1Client o = new Service1Client();
    bool result = o.Test(); // returns a True boolean

    System.Diagnostics.Debug.WriteLine(result); // True

    return View()
}

In my .cshtml file, I want to display this boolean. Or if the result from the controller class is a string, I want to display it. How do I do it? I tried ViewBag and it doesn't work because ViewBag only renders it for the first time. Please help!

<p>@result</p>

CodePudding user response:

you need to declare a model class, which should have a boo or string property depending on your requirement. then you can declare the object of that class (let's say obj) in your action method Test and then return like this return View(obj);

in view, you should have this on top and use its properties like @Model.<YourPropertyName>

@model <NameSpaceName>.<YouModelClassName>

I would recommend you to read about MVC, and How to pass data from controller to view, you will get a lot of examples.

CodePudding user response:

you have to include your data into model

[HttpPost]
public ActionResult Test()
{
    Service1Client o = new Service1Client();
    bool result = o.Test(); // returns a True boolean

    System.Diagnostics.Debug.WriteLine(result); // True

    return View(result)
}

and fix the view , add @model at the top

@model boolean

....

<p>@Model.ToString()</p>
  • Related