accessing viewbag in the view - asp.net-mvc

net MVC. I have assigned a list of objects to the viewbag property can anyone please tell me as to how i can get the list in the view to use it in the drop down list? here is my controller code & view code
Controller:
public ActionResult GetSection(int sectionId,int contactId)
{
ContactDetailSectionModel contactDetailSection = new ContactDetailSectionModel { SectionId = sectionId,ContactId=contactId };
contactDetailSection.FetchAllSubsections();
ContactDetailSectionModel customSections = new ContactDetailSectionModel();
customSections.FetchCustomSubSections();
if(customSections != null && customSections.ContactDetailSubSections != null)
{
ViewBag.CustomSubSections = customSections.ContactDetailSubSections;
}
return PartialView("~/Views/Contacts/Details/EditSection.cshtml", contactDetailSection);
}
View Code:
#Html.DropDownListFor(m => m.ContactDetailSubSections[1], new SelectList(ViewBag.CustomSubSections , "Name", "Name",Model.ContactDetailSubSections[1].Name))
#Html.TextAreaFor(m => m.ContactDetailSubSections[1].Text)

I think the first parameter in your #Html.DropDownlist should be string or some scalar quantity it cannot be a collection.

Related

How should I pass my query from controller using ToPagedList

Actually i want to integrate paging in my view page and for that I am retrieving data from below code and I am passing this code from controller to view but any how I am facing issue as
var model = (from sr in db.StudentRequests
join c in db.Classes
on sr.ClassId equals c.ClassId
select new { sr.StudentRequestId,c.ClassName,sr.CreatedOn,sr.Location,sr.PaymentMethod }).ToList().ToPagedList(page ?? 1, 1);
return View(model);
and I am getting issue as
Type : InvalidOperationException
Message : The model item passed into the dictionary is of type 'PagedList.PagedList`1[<>f__AnonymousType3`5[System.Int32,System.String,System.Nullable`1[System.DateTime],System.String,System.String]]', but this dictionary requires a model item of type 'PagedList.IPagedList`1[Student_Tutor.Models.StudentRequest]'.
Source : System.Web.Mvc
My view side is as
#using PagedList;
#using PagedList.Mvc;
#model IPagedList<Student_Tutor.Models.StudentRequest>
#if (ViewBag.StudentRequest != null)
{
var StudentRequestId = (int)Model.First().StudentRequestId;// Here I am able to get the StudentRequestId
var StudentRequestTimecount = StudentRequestTime.Where(d => d.StudentRequestId == StudentRequestId).ToList();
var TutorStudentRequestcount = TutorStudentRequest.Where(d => d.StudentRequestId == StudentRequestId).ToList();
#Html.Displayfor(model => model.First().StudentRequestId)// here only text is displaying as StudentRequestId
#Html.Displayfor(Model => Model.First().CreatedOn)//here only text is diplaying as created on
}
please expalin why I am getting this error?
Update 1
var model = (from sr in db.StudentRequests
join c in db.Classes
on sr.ClassId equals c.ClassId
select new Studentvm{ StudentRequestId = sr.StudentRequestId,ClassName= c.ClassName,
CreatedOn =Convert.ToDateTime(sr.CreatedOn),Location= sr.Location,PaymentMethod= sr.PaymentMethod })
.ToList().ToPagedList(page ?? 1, 1);
return View(model);
but I am getting error as
An exception of type 'System.NotSupportedException' occurred in Student_Tutor.dll but was not handled in user code
Additional information: LINQ to Entities does not recognize the method 'System.DateTime ToDateTime(System.Object)' method, and this method cannot be translated into a store expression.
This part of your LINQ code
select new { sr.StudentRequestId,c.ClassName,sr.CreatedOn,sr.Location,sr.PaymentMethod }
That is creating an annonymous object for each item in the result collection you get from your LINQ query and you are creating a PagedList from that. But your view is strongly typed to PagedList<StudentRequest>
The ideal solution is to create a viewmodel to represent the data needed for this view and use that in the projection part of your LINQ query
public class StudentVm
{
public int StudentRequestId { set;get;}
public string ClassName { set;get;}
public DateTime CreatedOn { set;get;}
public string Location { set;get;}
}
Now use this view model for your projection
select new StudentVm { StudentRequestId = sr.StudentRequestId,
ClassName= c.ClassName,
Location = sr.Location,
CreatedOn = sr.CreatedOn }
And make sure your view is not strongly typed to PagedList<StudentVm>
#using PagedList;
#model PagedList<YourNamespace.StudentVm>
<table>
#foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(a=> item.ClassName)</td>
<td>#Html.DisplayFor(a=> item.Location)</td>
<td>#Html.DisplayFor(a=> item.StudentRequestId)</td>
<td>#Html.DisplayFor(a=> item.CreatedOn)</td>
</tr>
}
</table>
Also, from your question, you are not really using the PagedList. To pass just a list of items, you do not need to convert that to PagedList<T> . You can simply send a List<StudentVm> from action method and change your view to be strongly typed to do that. Use PagedList if you are really using it (for paging)

How to Pass Kendo DropDownList DataTextField value to Controller

I have a Kendo DropDownList on the View and I want to pass its DataTextField value to the Controller and then pass and them on the labels in another View. Although I can pass DataValueField values to the Controller, I cannot pass DataTextField values. I tried to apply different scenarios but I could not. Any idea? On the other hand, if it is not possible, should the DataTextField values be populated again on the Controller and return to the other View?
View:
#model IssueViewModel
...
#Html.LabelFor(m => m.ProjectID)
#(Html.Kendo().DropDownList()
.Name("ProjectID")
.DataTextField("ProjectName")
.DataValueField("ProjectId")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetProjects", "Issue");
});
})
)
Controller:
public JsonResult GetProjects()
{
var projects = repository.Projects;
return Json(projects.Select(m => new { ProjectId = m.ID, ProjectName = m.Description }), JsonRequestBehavior.AllowGet);
}
/* I want to pass the DataTextField values to this
method and return them to the CreateManagement view */
public ActionResult Create(IssueViewModel issueViewModel)
{
return RedirectToAction("CreateManagement", issueViewModel);
}
Change your controller to this:
public JsonResult GetProjects()
{
var projects = repository.Projects;
return Json(projects.Select(m => new SelectListItem { ProjectId = m.Description, ProjectName = m.Description }).ToList(), JsonRequestBehavior.AllowGet);
}
Since the DropDownList uses DataTextField for the user and uses DataValueField for the server communications, so you have to use DataTextField value for both. Then you can use it for the next operations.
Edit: if you need both values on the controller, change JsonResult method to :
return Json(projects.Select(m => new SelectListItem { ProjectId = m.Description + "," + m.ID , ProjectName = m.Description }).ToList(), JsonRequestBehavior.AllowGet);
Now you can use both in the next operations just by spiting them like:
var _both = value.split(',');//value: returned value from the view

How to return distinct data to DropDownListFor?

I apply .Net MVC structure with C#. In the controller, I want to distinct specific column (IndustryName), and return the result to Html.DropDownListFor in view. But I get a running time error at view:
System.Web.HttpException: DataBinding: 'System.String' not include
'IndustryName' property.
Is there any one meet such problem, and how to solve it?
Thank you very much for your helping.
Controller:
public ActionResult Create()
{
var industrys = this._pmCustomerService.GetAll().Select (x => x.IndustryName).Distinct();
ViewBag.Industrys = new SelectList(industrys, "IndustryName", "IndustryName", null);
return View();
}
View:
#Html.DropDownListFor(model => model.IndustryName, (SelectList)ViewBag.Industrys)
Your query is returning IEnumerable<string> (you select only the IndustryName property in the .Select() clause. string does not contain an property named IndustryName so you get this error. Just change the SelectList to
ViewBag.Industrys = new SelectList(industrys);
This will bind the options value and display text to the value of IndustryName
The following sample implementation may help you fix the problem:
var industries= this._pmCustomerService.GetAll()
.GroupBy(ind => new { ind.IndustryName})
.Select(group => new SelectListItem
{
Text = group.First().Name,
Value = group .First().Name
}
);
ViewBag.Industries= industries;
You can find more about the 'GroupBy & Select' approach instead of using linq's Distinct(), here
View
#Html.DropDownList("ddlIndustries",(#ViewBag.Industries) as IEnumerable<SelectListItem>)
If you like to use DropDownListFor helper instead then modify view code as follows:
#{
var industries = ViewBag.Industriesas IEnumerable<SelectListItem>;
}
#Html.DropDownListFor(m=> industries , industries )
You get this error because you create SelectList with wrong collection. This should work i think.
var industrys = this._pmCustomerService.GetAll().Select(x => new SelectListItem
{
Value = x.IndustryName,
Text = x.IndustryName
}).Distinct();
ViewBag.Industrys = new SelectList(industrys);
return View();
You are only Selecting IndustryName which is obviously of type String, use DistinctBy() from MoreLinq by Jon Skeet, here is the reference SO post:
public ActionResult Create()
{
var industrys = this._pmCustomerService.GetAll().DistinctBy(x => x.IndustryName);
ViewBag.Industrys = new SelectList(industrys, "IndustryName", "IndustryName", null);
return View();
}

from data to controller and passing it to form

I'm doing my first steps in mvc and I need help.
I'm passing data from view to this controller and I need to pass the selected items with there details to a different view (that is a form that the user add his email details) and I cant figure out how to .
This is how I'm getting the details to the controller from the submitted form
public ActionResult list()
{
var AllItems = db.menu.ToList();
Mapper.CreateMap<Menu, SelectableMenu>();
return View(AllItems.Select(m => new SelectableMenu { price = m.price, MenuId = m.MenuId, Name = m.Name })
.ToList());
}
[HttpPost]
public ActionResult List(IEnumerable<SelectableMenu> item)
{
var userSelectedMenu = item.Where(m => m.IsSelected).Select(m => m.Name + m.price + m.MenuId);
if (userSelectedMenu != null && userSelectedMenu.Any())
{
return View("bla");
}
return View();
}
Use method ReditectToActionstring actionName, string controllerName, Object routeValues)
for details go to: http://msdn.microsoft.com/en-us/library/dd460311(v=vs.108).aspx
You can return different view using return View("ViewName",model)
For eg:
[HttpPost]
public ActionResult List(IEnumerable<SelectableMenu> item)
{
var userSelectedMenu = item.Where(m => m.IsSelected).Select(m => m.Name + m.price + m.MenuId);
if (userSelectedMenu != null && userSelectedMenu.Any())
{
return View("YourDiffrentViewName",userSelectedMenu); // This will pass your model to your Different view
}
return View();
}
Then in your new view you will have to strongly typed it with your model.
For eg :
Your view will be as follows:
#model ProjectName.models.YourClassName //Your class/model namespace
#using(Html.BeginForm())
{
#Html.TextBoxFor(m => Model.Property) //This will create textbox for your property
<input type="submit" value="Submit" />
}
For more on stronly typed views visit:
http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/strongly-typed-views-in-mvc/
http://www.howmvcworks.net/OnViews/BuildingAStronglyTypedView
You will need twosteps for this
Step 1
Make a model(it is more effective) use it in a view to pass your data to controller through post in submission of form.
Step 2
Receive the data into the controller method then use
return View("yourNewpage","yourdatamodelobject"); in the controller action to pass the data in the action result view of another page.
Alternatively, if the view is in another controller
then you can receive data here in the post action method and use Return RedirectToAction("ActionName", "ControllerName", "DataModelObject") to pass to a diffrent controller

Creating a dropdown list in MVC nhibernate

I'm creating an application in hibernate where i need to create a dropdown list in my Create View.
The dropdownlist items are fetched through a function called getHobbytype() and from that I need to store the selected value into a different database.
I have written this in my controller:
ViewData["Hobby_type"] =
new SelectList(new Hobby_MasterService().GetHobbyType(),"Hobby_Types");
And this in my Create View:
#Html.DropDownListFor(Model =>
Model.Hobby_Types,(IEnumerable<SelectListItem>)ViewData["Hobby_type"])
Through this I'm able to create the dropdown list but it is giving me this error inside my view on the dropdown:
There is no ViewData item of type 'IEnumerable' that has the key 'Hobby_Types'.
Here is my GetHobbyType Method:
public IList<String> GetHobbyType()
{
log.Debug("Started");
ISession session = DataAccessLayerHelper.OpenReaderSession();
IList<String> htype = null;
ITransaction transaction = null;
try
{
transaction = session.BeginTransaction();
htype = session.CreateSQLQuery("SELECT Hobby_Types FROM Hobby_Type").List<String> ();
session.Flush();
transaction.Commit();
}
catch (Exception ex)
{
if (transaction != null && transaction.IsActive)
transaction.Rollback();
log.Error(ex);
}
log.Debug("End");
return htype;
}
Please tell me where I'm going wrong.
Is this a typo:-
#Html.DropDownListFor(Model =>
Model.Hobby_Types,(IEnumerable<SelectListItem>)ViewData["Type"])
Should it not be
#Html.DropDownListFor(Model =>
Model.Hobby_Types,(IEnumerable<SelectListItem>)ViewData["Hobby_type"])
Also your error says 'IEnumerable' that has the key 'Hobby_Types'.
The key in ViewData is case sensitive (not to mention the error has an S on the end)
I would also reccomend using a ViewModel rather than ViewData. See this Google search
edit The GetHobbyType Method returns a List so try this:-
ViewData["Hobby_type"] =
new SelectList(
new Hobby_MasterService().GetHobbyType()
.Select(x => new SelectListItem { Text = x, Value = x }).ToList()
,"Hobby_Types");
I also suggest looking at using a viewmodel as it will save you lots of headaches!
You can try this all.
You have to write a service named GetAllStudents()
public IList<Student> GetAllStudents()
{
log.Debug("Started");
ISession session = DataAccessLayerHelper.OpenReaderSession();
IList<Student> students = null;
ITransaction transaction = null;
try
{
transaction = session.BeginTransaction();
ICriteria criteria = session.CreateCriteria(typeof(Student));
students = criteria.List<Student>();
session.Flush();
transaction.Commit();
}
catch (Exception ex)
{
if (transaction != null && transaction.IsActive)
transaction.Rollback();
log.Error(ex);
}
finally
{
if (transaction != null)
transaction.Dispose();
if (session != null && session.IsConnected)
session.Close();
}
log.Debug("End");
return students;
}
In controller:
ViewBag.std = new StudentService().GetAllStudents(); // ViewBag.std will hold all students.
In create View:
#Html.DropDownListFor(model => model.Name, new SelectList(ViewBag.std, "Id", "Name"), "-- Select --")
First parameter is responsible for Linq expression for class property which you want to place in dropdown.
Second one is IEnumerable item list.
Third data value field.(Primary key)
Last one is Data text field which you want to display in drop down list.

Resources