Two render bodies in layout page? - asp.net-mvc-3

I understand that only 1 RenderBody can exist in the MVC3 layout page however I want to attempt to create another. Maybe I'm looking at it the wrong way... Ideally I want to add a testimonial section that pulls in from the DB and display 1 testimonial at a time and a different 1 for each page refresh or new page. What is the best way to go about this?
Controller
CategoryDBContext db = new CategoryDBContext();
public ActionResult Testimonial(int id)
{
TestimonialModel model = db.Testimonials.Find(id);
return View(model);
}
Model
public class TestimonialModel
{
public int ID { get; set; }
public int CategoryID { get; set; }
public string Data { get; set; }
}
public class CategoryDBContext : DbContext
{
public DbSet<TestimonialModel> Testimonials { get; set; }
}
The View is in a folder called CategoryData.

You need to be use:
Layout:
#RenderSection("Testimonial", false) #*false means that this section is not required*#
and in you View
#section Testimonial{
}

I would use #Html.Action()
Here is a great blog post about using them: https://www.c-sharpcorner.com/article/html-action-and-html-renderaction-in-Asp-Net-mvc/
This would allow you to have a TestimonialController that can take in values, query for data and return a partial view.

Related

How to update hierarchical ViewModel?

I am stuck with this problem.
I have a model AssessmentModel defined like this:
public class AssessmentModel
{
public Respondent Respondent { get; set; }
public List<CompetencyModel> Competencies { get; set; }
}
public class CompetencyModel
{
public int Id { get; set; }
public string Name { get; set; }
public List<ResultModel> Results { get; set; }
}
public class ResultModel
{
public int Id { get; set; }
public int Score { get; set; }
}
All I need is to set value to the Score property of ResultModel.
Score is the only editable property here.
And I have just 1 View only, this view has a #model List, it displays a list of CompetencyModel items with Edit button for each one.
When I click the Edit button, the Id of CompetencyModel is passed to the same View, and the View draws an Edit form for ResultModel items that belong to the selected CompetencyModel.
However the form for ResultModel items exists on the same View, and the model of the View is still #model List.
How can I get to the Score property by using bindable Html.EditorFor(m=>m.Score) helper for each ResultModel item?
The View is defined like this:
#model List<CompetencyModel>
#foreach(var comp in Model)
{
<p>#comp.Name</p>
Edit
}
In the controller I set ViewBag.CurrentId = comp.Id, and at the bottom of the View:
if(ViewBag.CurrentId != null) //draw a form for ResultModel items
{
// What should I do now?
// how cant I use Html.EditorFor(m=>...) if the Model is still List<CompetencyModel>
}
I need to get to a single ResultModel entity to set a value to a Score property.
Thank you.
You should be able to get this done using Linq. Consider having the following code segment in the your last if statement
var result = Model.Results.FirstOrDefault(r => r.Id == ViewBag.CurrentId);
I dont have a IDE with me, so watchout for syntext errors

select the value to populate html.dropdownlist

I have two classes as follows
public class ODCTE_Major
{
public int ODCTE_MajorId { get; set; }
public string OfficialMajorName { get; set; }
public string MajorCode { get; set; }
... More unrelated code ....
}
AND
public class CareerMajor
{
...lots of unrealted code to this question left out
public int ODCTE_MajorId { get; set; }
public virtual ODCTE_Major ODCTE_Major { get; set; }
}
I added a controller with CRUD methods and in the create.cshtml there is this line
<div class="editor-field">
#Html.DropDownList("ODCTE_MajorId", String.Empty)
#Html.ValidationMessageFor(model => model.ODCTE_MajorId)
</div>
The select list populates it with the OfficialMajorName from ODCTE_Major. I need the select list to populate with the MajorCode or a value that looks like MajorCode - OfficialMajorName.
Could someone provide assistance for how this is done, please?
Thanks.
Add this to ODCTE_Major:
public string MajorDisplayName
{
get { return string.Format("{0} - {1}", MajorCode, OfficialMajorName); }
}
This is just a read only property used to create the display text in the format you want the menu to use.
Then in CareerMajor, add:
public IEnumerable<ODCTE_Major> Majors{ set; get; } // Thank you Shyju!
This will give you a place in your view model to pass the list of Majors you want in your menu to the view.
Then in your action method when you're creating a CareerMajor view model to send to the view, populate the new IEnumberable with the ODCTE_Major entities you'd like displayed in your menu.
On the view page:
#Html.DropDownListFor(m => m.ODCTE_MajorId, new SelectList(Model.Majors, "ODCTE_MajorId", "MajorDisplayName", Model.ODCTE_MajorId), "Select One")
This creates a SelectList to populate the drop down with. The SelectList constructor is saying use ODCTE_MajorId as the value for a SelectListItem in the menu, and to use MajorDisplayName as the text to actually display in the menu. It sets the selected value, if there is one, and adds a null item with the text "Select One" to the top of the menu. Feel free to take that final argument out if you don't want the null text.
Have your ViewModel hold a Collection property to represent all available Majors (for poulating the Dropdown)
public class CareerMajor
{
//other proiperties
public int ODCTE_MajorId { get; set; }
public IEnumerable<ODCTE_Major> Majors{ set; get; }
}
And in your GET Action, fill it and send it to your strongly typed view
pubilc ACtionResult Create()
{
var viewModel=new CareerMajor();
viewModel.Majors=db.GetllAllMajors(); // getting a list of ODCTE_Major objects
return View(viewModel);
}
and in the View, use the DropDownListFor HTML Helper method.
#model CareerMajor
#Html.BeginForm())
{
#Html.DropDownListFor(m=>m.ODCTE_MajorId,
new SelectList(Model.Majors,"ODCTE_MajorId ","MajorCode"),"select one..")
//other elements
}
In your controller action:
ViewBag.ODCTE_MajorId = new SelectList(availableMajors, "ODCTE_MajorId", "MajorCode");
*second and third parameters are the names of the value and text fields respectively
Then in your view:
#Html.DropDownList("ODCTE_MajorId", String.Empty)
where availableMajors is an IEnumerable that contains the majors you want to list.

To show Create and detail view in one view using mvc3

Hi i want to show a page where i'm allowing user to create a new record and show the other related records of same table below .....
i need to add data in Hobbydetail class:
public class HobbyDetail
{
public virtual HobbyMasters Hobbymaster { get; set; }
public virtual Course course { get; set; }
public virtual StudyMedium StudyMedium { get; set; }
public virtual decimal Fees { get; set; }
}
I want my view "Create" to let the user create a new record and to also to show existing record below it...
I Dont want to use a viewmodel...
Can sumbody help me
Thanx in advance
One way to accomplish this is: In your controller, create a child action that renders the list, then render that action in your "Create" view using Html.RenderAction (also see this). I have included some code below (I have not tested this, but it should give you the basic idea). Please note this is not the only way to accomplish this - You could use a partial view see this. Please also understand the difference between html.RenderAction and html.Action, see this.
//In HobbyDetail Controller
[HTTPGet]
public ActionResult Create()
{
var model = new HobbyDetail ();
return View(model);
}
[HTTPPost]
public ActionResult Create(HobbyDetail model)
{
if(ModelState.isValid)
{
//logic to persist model
}
else
{
//logic when validation fails...
}
}
[ChildActionOnly]
public ActionResult ListAll()
{
List<Hobbydetail> model = //query to DB, or Data store to get Hobbydetails
return View(model);
}
//View for ListAll
#model List<HobbyDetail>
{
Layout = null; //No layout here...
}
<ul>
#foreach(var h in Model)
{
<li>#h.HobbyMasters.Name</li> //for example...
}
</ul>
//View for Create
#model HobbyDetail
...
#{html.renderAction("ListAll");}

Html.Editor() helper in ASP.NET MVC 3 does not work as expected with array in model

In my ASP.NET MVC 3 application I have classes like the following:
public class Localization<T>
{
public int VersionID { get; set; }
public T Value { get; set; }
...
}
public class Localizable<T>
{
public Localization<T>[] Name { get; set; }
...
}
Then, I have the following view:
#model dynamic
...
#for (int i = 0; i < VersionCount; i++)
{
...
#Html.Editor(string.Format("Name[{0}].Value", i))
...
}
Now, when I display this view, passing a subclass of Localizable<string> as the model, the textboxes for the strings are rendered, but they are empty. If I replace #Html.Editor(string.Format("Name[{0}].Value", i)) with #InputExtensions.TextBox(Html, string.Format("Name[{0}].Value", i), Model.Name[i].Value), the textboxes are correctly filled with values from the model. However, using TextBox instead of Editor is not an option for me, because I want to use different editor templates for different types of T. So, what am I doing wrong, or is it a bug in MVC, and is there any workaround?
you can use attribute UIHint("MyUIHintName").
public class Localizable<T>
{
[UIHint("MyUIHintName")]
public Localization<T>[] Name { get; set; }
...
}
Then you need to create folder Views/Shared/EditorTemplates/. Next you need create Razor View
Views/Shared/EditorTemplates/MyUIHintName.cshtml
In this view you can write logic for every type, for example:
#model dynamic
#if(ViewData.ModelMetadata.ModelType.Name=="string")
{
//Do something
}
#if(ViewData.ModelMetadata.ModelType.Name=="int")
{
//Do something
}

Self referring hierarchical data binding

I'm using Extensions for ASP.NET MVC Q3 2011(open source version) with Razor engine and Asp.net MVC3 architecture.
I want to bind a grid to a entity in my database which has self referring structure (like a tree). Therefore, I can not define it like examples with fixed levels, because I do not know how many levels this grid has. So, I want to bind my grid dynamically to a model.
public class Category : Entity
{
public virtual int Id {private set; get; }
public virtual string Title { set; get; }
public virtual string Description { set; get; }
public virtual string ParentsPath { set; get; }
public virtual IList<Category> Children { get; private set; }
public virtual Category Parent { get; set; }
}
I'm also using Fluent NHibernate and because of that I store children and parent in my entity.
Is there a way to do this? I couldn't find anything in documentations.
Am I missing something? because in Ajax and Winform components, it has been implemented.
Thanks.
You cannot do it automatically, You need a foreach iteration and generating the items and then add them to the tree manually.
I did it for PanelBar when I needed to show a hierarchicy.
Here is an example :
#(Html.Telerik().PanelBar()
.Name("Details")
.ExpandMode(PanelBarExpandMode.Multiple)
.Items(items =>
{
var parent = Model.ParentWorkItem;
List<WorkItem> lst = new List<WorkItem>();
while (parent != null)
{
lst.Add(parent);
parent = parent.ParentWorkItem;
};
for (int i = lst.Count-1; i >=0;i-- )
{
parent = lst[i];
items.Add()
.Expanded(false)
.Text("...")
.LoadContentFrom(...);
}
items.Add()
.Expanded(true)
.Text(...)
.Content(....);
})
)
Hope to be helpful.

Resources