1
votes

I developing WEB API project using .net C#

I need to get the value from controller.cs file and use that value into View(.cshtml) file.

My Controller Code:

HomeController.cs

 XmlDocument doc = new XmlDocument();
 doc.Load(httpWebResponse.GetResponseStream());

        XmlElement TransID = (XmlElement)doc.SelectSingleNode("/CensusUploadResponse/TransactionID");
        if (TransID != null)
        {
            string ResultID = TransID.InnerText;

        }

I need to pass the ResultID to Index.cshtml(Ex:ResultID = 17)

MY View .cshtml file code:

Index.cshtml

   <div runat="server" id="CensusuploadDiv"  style="border:1px solid black; width:420px;">

  </div>

I need to assign that ResultID value to CensusuploadDiv.

I try with following method using ViewBag. but's it's not working.

Assign ResultID to ViewBag like below

  if (TransID != null)
        {
            string ResultID = TransID.InnerText;
            ViewBag.Test2 = ResultID;
        }

and i get the value in index file like below

<div runat="server" id="CensusuploadDiv"  style="border:1px solid black; width:420px;">
    @ViewBag.Test2
 </div>

But value not bind to div.

2
What do you mean by "bind to div"?DavidG
@DavidG I need to assign the value to div.Gurunathan
@DavidG Just i need to display 17 in DivGurunathan
Your code should work unless the value of XmlElement TransID = (XmlElement)doc.SelectSingleNode("/CensusUploadResponse/TransactionID") is null?DavidG
Yes, only show the value when it's not nullGurunathan

2 Answers

1
votes

I find out solution for my problem by Using TempData.

TempData help me lot...

I use TempData as follow in HomeController.cs

string result = strBind.ToString();
TempData["Result"] = result;

In view.cshtml

@TempData["Result"]

It's work fine for me...

0
votes

Do you develop Web API or ASP.NET MVC project? Best way to access values from controller in view is to use strongly typed models:

@model int

<div>@Model</div>

Example: Index.cshtml

@model int

<div>@Model</div>

HomeController.cs

public ActionResult GetId()
{
   int id;
   ....
   return View(id);
}

Please note, that WebApi and MVC controllers are slightly different. But this is how it works.