Pages

Tuesday, 19 November 2019

Putting model data in Viewbag



Putting Model in viewbag is the easiest way to flow A model data controller to a view. Let see a case, Suppose You’re editing a student record, On the editing page, you need to fill student details in related textbox and different type of dropdown list, which data is coming from database i.e. course , session, etc.

Normally we bind one model control to a view at a time. But if you are putting the model in a viewbag then you can transfer any number of models to a view. The following code will show you, Getting course record from the controller and filling it in the drop-down list at the view 


Model



public class CourseModel
    {
        public string ID { get; set; }
        public string CourseName { get; set; }
        public string Description { get; set; }
    }


Controller


public ActionResult StudentEdit(string id)
        {
            List<CourseModel> CourseData = new List<CourseModel>();
            CourseData = ob2.GetCourseAll();
            ViewBag.Course = CourseData;
            return View();
        }


View



<select id="ddlCourse" class="form-control" >
    <option value="">Select Course</option>
    @{
        var data = ViewBag.Course;
    }
    @foreach (var item in data)
    {
        <option value="@item.ID">@item.CourseName</option>
    }
</select

No comments:

Post a Comment