How do I show webgrid content and insert data form in one view in mvc3?

Go To StackoverFlow.com

0

I'm not able to show web grid contain and insert data form in only one view

I have created a application where on index.cshtml i'm displaying all employee details.

index.cshtml

<div>
WebGrid Control
<br /><br />
@Html.Partial("_WebGridPartial")
</div>

in which i have create partial view which display data.

Now I have created another view called Create.cshtml which takes employee details and save into database.

But if i want to show both grid and create employee form then how can i use it? as problem is when i show data it is using @model IEnumerable<MvcGrid.Models.EmpData> which is of type IEnumerable and inside Create View for input fields I need to use @model MvcGrid.Models.EmpData and only one model statement can be used.

2012-04-05 15:08
by Neo


1

You could pass index.cshtml a ViewModel that contains both your grid data and a ViewModel for an Employee.

e.g.

public class EmployeesViewModel
{
    public IEnumerable<EmployeeViewModel> employeesForGrid { get; set; }
    public EmployeeViewModel employeeForEdit { get; set; }
}

In your controller...

public ViewResult Index()
{
    IEnumerable<Employee> employees = _employeeRepo.GetEmployees();
    IEnumerable<EmployeeViewModel> employeesForGrid = MapEmployeesForView(employees);

    var model = new EmployeesViewModel()
    {
        employeesForGrid = employeesForGrid,
        employeeForEdit = new EmployeeViewModel(); 
    };

    return View(model);
}

Then index.cshtml:

@model EmployeesViewModel

@{Html.RenderPartial("_WebGridPartial", Model.employeesForGrid);}
<br/><br/>
@{Html.RenderPartial("_Create", Model.employeeForEdit);}
2012-04-05 18:30
by ngm
plz tell more about MapEmployeesForView in your cod - Neo 2012-04-09 13:32
The MapEmployeesForView is simply to illustrate that you might want to map MvcGrid.Models.EmpData to a ViewModel class rather than having your domain entity passed straight to the view. You don't necessarily have to use EmployeeViewModel though, you could use your MvcGrid.Models.EmpData class directly, just update EmployeesViewModel accordingly - ngm 2012-04-09 13:33
public class ViewModel { public IEnumerable employeesForGrid { get; set; } public ViewModel employeeForEdit { get; set; } } public ActionResult Index() { IEnumerable employees = EmployeeModel.GetEmpData(); IEnumerable employeesForView = MapEmployeesForView(employees); var model = new ViewModel() { employeesForGrid = employeesForView, employeeForEdit = new ViewModel() }; //MvcGrid.Models.EmployeeModel.GetEmpData() return View(model); } MapEmployeesForView - Neo 2012-04-09 13:43
Ads