Home > Software engineering >  cant get the data in viewbag
cant get the data in viewbag

Time:09-19

@model SPES_PPS.Models.Benificiary

<h3>My partial view</h3>

<table>

@foreach (var item in ViewBag.bendetails)
{
    <tr>
        <td>Beni ID</td>
        <td>@item.benID</td>
    </tr>
    <tr>
        <td></td>
        <td></td>
    </tr>
}


</table>

my Jquery in view

controller

   // GET: Benificiary/Details/
    public ActionResult Details(int id)
    {
     //var benificiary = db.Benificiaries.Where(x => x.id == id).FirstOrDefault();
            //ViewBag.showdetails = benificiary;
//return PartialView("Partial_Details");
            
   Benificiary benificiary = db.Benificiaries.Find(id);
                if (benificiary == null)
                {
  return HttpNotFound();
                }
   ViewBag.bendetails = benificiary;
                return PartialView("Partial_Details", benificiary);

        }
    }

CodePudding user response:

In your Action, You return a PartialView with a model, Why you get data from ViewBag?

You use db.xxx.Find(id) to select a Benificiary, Why you use foreach()?

You can try to change your code like in Partial view.

@model SPES_PPS.Models.Benificiary

<h3>My partial view</h3>

<table>
        <tr>
            <td>Beni ID</td>
            <td>@Model.benID</td>
        </tr>
        <tr>
            <td></td>
            <td></td>
        </tr>    
    
    </table>

CodePudding user response:

you can directly access data from model like @Model.itemName

CodePudding user response:

Since you are passing beneficiary object to view which accepts an object of the same type, you can access it in your View as the following:

@Html.DisplayFor(model => model.benID)

or

@Model.benID

However, if you want to use ViewBag to pass data from Controller to View, use ViewDate.

In Controller,

ViewData["beneficiary"] = benificiary;

In View, the assigned data will be string, so you need to cast it to beneficiary object

@{
    var beneficiary = ViewData["beneficiary"] as Beneficiary;
}
<span>@beneficiary.benID</span>
  • Related