Asp.Net MVC 5 How to send ViewBag in partial view

I have a _LoginPartial View and want to send data to it with a ViewBag, but the controller from which I send data has no view.

public PartialViewResult Index()
    {
        ViewBag.sth = // some data
        return PartialView("~/Views/Shared/_LoginPartial.cshtml");
    }

This code did not work for me.

+4
source share
4 answers

You seem to expect that this action Indexis called when you do: @Html.Partial('_LoginPartial'). It will never happen. Partialjust does partial browsing through Razor with the current view context and spills out the generated HTML.

If you need additional information for partial, you can specify a custom ViewDataDictionary:

@Html.Partial("_LoginPartial", new ViewDataDictionary { Foo = "Bar" });

What you can then get through partial through:

ViewData["Foo"]

, , , . _LoginPartial , , . , , _LoginPartial, MVC auth, .

, , , , , , Html.Action Html.Partial:

@Html.Action("Index")

, .

+6

.

public PartialViewResult Index()
{
    var data = // some data
    return PartialView("~/Views/Shared/_LoginPartial.cshtml", data);
}

public class MyModel
{
    public int Prop1 { get; set; }
    public int Prop2 { get; set; }
}

public PartialViewResult Index()
{
    var data = new MyModel(){ Prop1 = 5, Prop2 = 10 };
    return PartialView("~/Views/Shared/_LoginPartial.cshtml", data);
}
0

viewBag , , ViewBag JSON , @Html.Raw(Json.Encode(ViewBag.Part));

.

 public async  Task<ActionResult> GetJobCreationPartialView(int id)
        {
            try
            {
                var client = new ApiClient<ServiceRepairInspectionViewModel>("ServiceRepairInspection/GetById");
                var resultdata = await client.Find(id);

                var client2 = new ApiClient<PartViewModel>("Part/GetActive");  
                var partData = await client2.FindAll(); 

                var list = partData as List<PartViewModel> ?? partData.ToList();
                ViewBag.Part = list.Select(x => new SelectListItem() {Text = x.PartName, Value = x.Id.ToString()});
                return PartialView("_CreateJobCardView" ,resultdata);
            }
            catch (Exception)
            {

                throw;
            }

        }

, viewBag.

0

-, . @Html.Partial("_SomeView"), Index(), , . @Html.Partial("_SomeView") _SomeView.cshtml ViewContext.

, , . : ControllerBase BaseController, .

Extension Method:

Helper:

public static class ControllerExtensions
{
    public static string GetCommonStuff(this ControllerBase ctrl)
    {
        // do stuff you need here
    }
}

View:

@ViewContext.Controller.GetCommonStuff()

Basecontroller

Controller:

public class BaseController : Controller
{
    public string GetCommonStuff()
    {
        // do stuff you need here
    }
}

Other controllers:

public class SomeController : BaseController
...
...

View:

@((ViewContext.Controller as BaseController).GetCommonStuff()) 
-1
source

All Articles