I have a partial view where I pass the model name to populate it, is there any way to pass model name as a parameter based on the controller action executed?
<div id = "Details" >
<% List<Freshmen>() = model based on controller action executed %>
<% using (Html.BeginForm("FreshmenDetails", "Students")) %>
<% { %>
<% Html.RenderPartial("FreshmenDetails", new List<Freshmen>()); %>
<% } %>
</div>
Controller Action:
public ActionResult FreshmenDetails(string id)
{
DataContext Student = new DataContext();
var FreshmenDetails = Student.Freshmen.Where(a => Convert.ToInt64(a.Id) == Convert.ToInt64(id)).ToList();
return PartialView("FreshmenDetails", FreshmenDetails );
}
I have 3 more Actions each for SophomoreDetails(),JuniorDetails(),SeniorDetails()
Currently I am displaying Partial View like this:
<div id = "Details" >
<% using (Html.BeginForm("FreshmenDetails", "Students")) %>
<% { %>
<% Html.RenderPartial("FreshmenDetails", new List<Freshmen>()); %>
<% } %>
<% using (Html.BeginForm("SophomoreDetails", "Students")) %>
<% { %>
<% Html.RenderPartial("SophomoreDetails", new List<Sophomore>()); %>
<% } %>
<% using (Html.BeginForm("JuniorDetails", "Students")) %>
<% { %>
<% Html.RenderPartial("JuniorDetails", new List<Junior>()); %>
<% } %>
<% using (Html.BeginForm("SeniorDetails", "Students")) %>
<% { %>
<% Html.RenderPartial("SeniorDetails", new List<Senior>()); %>
<% } %>
</div>
I want something like:
<div id = "Details" >
<% using (Html.BeginForm("FreshmenDetails", "Students")) %>
<% { %>
<% Html.RenderPartial("FreshmenDetails", new List<Freshmen>()); %>
<% } %>
</div>
I am having a hard time figuring out exactly what your after. That being said, have you tried using reflection?
return PartialView(Model.GetType().Name, new { // Partial View object });
Further more, you can use Model.GetType().Name to get the model object name and use it where you want.
That should work for you.
Related
Attempting to make a Questionnaire page for a client. It's a pretty large list of questions, so I've broken it up into sections and subsections to make it easier for the user to navigate. The problem seems to be that in order to build the page, I iterate over the sections/subsections/questions, and not the answers. Answers are stored in a dictionary, with the key being the ID number of the associated question.
The ViewModel passed to the view is UserQuestionnaireViewModel, QuestionnaireViewModel has a list of Sections, each of which has a list of SubSections, each of which has a list of Questions. The Answers Dictionary gets all Answers linked to the relevant user, indexed by the Question they're linked to. Missing Answers are populated here, the View breaks if they're missing.
Model
public class UserQuestionnaireViewModel {
ClientPortalDbContext db = new ClientPortalDbContext();
public QuestionnaireViewModel Questionnaire { get; set; }
public Dictionary<Int32, QuestionnaireAnswer> Answers { get; set; }
public UserQuestionnaireViewModel() { }
public UserQuestionnaireViewModel(Int32 userID) {
Questionnaire = new QuestionnaireViewModel();
Answers = new Dictionary<Int32, QuestionnaireAnswer>();
List<QuestionnaireAnswer> answerList = db.QuestionnaireAnswers.Where(a => a.UserID == userID).ToList();
foreach (QuestionnaireAnswer answer in answerList) {
Answers.Add(answer.QuestionID, answer);
}
foreach (QuestionnaireViewModel_Section section in Questionnaire.Sections) {
foreach (QuestionnaireViewModel_SubSection subsection in section.SubSections) {
foreach (QuestionnaireQuestion question in subsection.Questions) {
if (!Answers.ContainsKey(question.ID)) {
Answers.Add(question.ID, new QuestionnaireAnswer() {
QuestionID = question.ID,
UserID = userID,
AnswerBool = false,
AnswerText = ""
});
}}}}}}
The Section and SubSectionclasses contain a name string, and a List of whatever comes under them (SubSection and Question respectively). Question has an id int, string for question text, and bools for what fields to show.
View
<div class="content-wrapper">
<% using (Html.BeginForm("Save", "Questionnaire", new { input = Model.Answers })) { %>
<%: Html.AntiForgeryToken()%>
<%: Html.ValidationSummary(true)%>
<fieldset>
<ul class="questionnaire-tabs">
<% Int32 tabIndex = 0; %>
<% foreach (clientportal.Models.QuestionnaireViewModel_Section section in Model.Questionnaire.Sections) { %>
<% tabIndex++; %>
<li id="<%: "tab-button-" + tabIndex.ToString()%>" data-tab="<%: "tab-" + tabIndex.ToString()%>">
<%: section.Name%>
</li>
<% } %>
</ul>
<div class="clear"></div>
<% tabIndex = 0; %>
<% foreach (clientportal.Models.QuestionnaireViewModel_Section section in Model.Questionnaire.Sections) { %>
<% tabIndex++; %>
<div class="questionnaire-tab-content" id="<%: "tab-" + tabIndex.ToString()%>">
<p><%: section.Heading%></p>
<% foreach (clientportal.Models.QuestionnaireViewModel_SubSection subsection in section.SubSections) { %>
<h4><%: subsection.Name%></h4>
<p><%: subsection.Heading%></p>
<div>
<table class="questionnaire-table">
<% foreach (clientportal.Models.QuestionnaireQuestion question in subsection.Questions) { %>
<% clientportal.Models.QuestionnaireAnswer answer = Model.Answers[question.ID]; %>
<% if (question.Enabled) { %>
<tr>
<td class="label-col">
<%: Html.Label(question.Text) %>
<%: Html.Hidden("Model.Answers.Index", question.ID) %>
<%: Html.Hidden("Model.Answers[" + question.ID + "].ID", answer.ID) %>
<%: Html.Hidden("Model.Answers[" + question.ID + "].QuestionID", answer.QuestionID) %>
<%: Html.Hidden("Model.Answers[" + question.ID + "].UserID", answer.UserID) %>
</td>
<td class="bool-col">
<% if (question.ShowCheckBox) { %>
<%: Html.CheckBox("Model.Answers[" + question.ID + "].AnswerBool", answer.AnswerBool) %>
<% } else { %>
<%: Html.Hidden("Model.Answers[" + question.ID + "].AnswerBool", answer.AnswerBool) %>
<% } %>
</td>
<td class="text-col">
<% if (question.ShowTextBox) { %>
<%: Html.TextBox("Model.Answers[" + question.ID + "].AnswerText", answer.AnswerText) %>
<% } else { %>
<%: Html.Hidden("Model.Answers[" + question.ID + "].AnswerText", answer.AnswerText) %>
<% } %>
</td>
</tr>
<% } %>
<% } %>
</table>
</div>
<% } %>
</div>
<% } %>
</fieldset>
<h4>Please ensure you have checked all sections of the Questionnaire before saving.</h4>
<input type="submit" value="Save Answers" />
<% } %>
</div>
On submitting the form, it goes through to the Controller fine (The Controller takes a Dictionary<Int32, QuestionnaireAnswer> for this Action), except the model sent through has 0 rows and fails ModelState.IsValid
Looking around SO has given me the idea that this is an issue with MVC and Dictionaries in general, or simply failure to bind the dictionary. Any answers in the Database are displayed correctly, it's simply the inability to get the contents of the page back to the controller that's preventing me moving onwards.
Don't use foreach loop. Use for loop.
One more thing always use Html.HiddenFor(model.xxxx) and for other controls also.
If you use for loop along with HiddenFor this will automatically create appropriate name for controls
If it's possible to separate out database operation from MVC model then it's best.
Using this code within an aspx file
<% if(storeid=1) { %>
<script src="//d3c3cq33003psk.cloudfront.net/opentag-1234-abcd.js" async defer></script>
<% } %>
<% else if(storeid=2) { %>
<script src="//d3c3cq33003psk.cloudfront.net/opentag-1234-efgh.js" async defer></script>
<% } %>
<% else if(storeid=3) { %>
<script src="//d3c3cq33003psk.cloudfront.net/opentag-1234-ijklmn.js" async defer></script>
<% } %>
<% else if(storeid=4) { %>
<script src="//d3c3cq33003psk.cloudfront.net/opentag-1234-opqrs.js" async defer></script>
<% } %>
Compiling this gives me this error
Compiler Error Message: CS1525: Invalid expression term '<'
Source Error:
Line 62:
Line 63: // Specific Code test 17.4.2014
Line 64: <% if(storeid=1) { %>
Line 65: <script src="//d3c3cq33003psk.cloudfront.net/opentag-1234-abcd.js" async defer> </script>
Line 66: <% } %>
All of the <% and %> look ok. Where is it falling down?
It's storeid == 1, not storeid=1.
Replace this line:
<% if(storeid=1) { %>
With:
<% if( storeid == 1 ) { %>
By the way, this is true for all of the rest equality checks in the other lines of code.
Your storeid='1' is wrong and the rest of your else statement. it should be ==.
storeid == 1 and not storeid=1.
<% if(storeid=1) { %>
should be
<% if(storeid==1) { %>
<script src="//d3c3cq33003psk.cloudfront.net/opentag-1234-abcd.js" async defer></script>
<% } %>
<% else if(storeid==2) { %>
<script src="//d3c3cq33003psk.cloudfront.net/opentag-1234-efgh.js" async defer></script>
<% } %>
<% else if(storeid==3) { %>
<script src="//d3c3cq33003psk.cloudfront.net/opentag-1234-ijklmn.js" async defer></script>
<% } %>
<% else if(storeid==4) { %>
<script src="//d3c3cq33003psk.cloudfront.net/opentag-1234-opqrs.js" async defer></script>
<% } %>
I have DropDownList and Textbox on my page.
DropDownList show data from DataBase(Table "List").
When I choose one line in DropDownList I want to see it in Textbox, make changes and save this line into DataBase(Table "Text") after press "OK".
Please tell me, how to do this?
Code:
Controller.cs:
public ActionResult Create(Model model)
{
var viewModel = new ISMSViewModel
{
Model = new Model(),
};
return View(viewModel);
}
[HttpPost]
public ActionResult Create(Model model, int i)
{
try
{
sysDB.AddToActives(model);
sysDB.SaveChanges();
return RedirectToAction("Browse");
}
}
ListText.ascx:
<%: Html.EditorFor(model => model.Model, new { Lists = Model.Lists } %>
<%: Html.Label("List") %>
<%: Html.DropDownList("ListId", new SelectList(ViewData["Lists"] as IEnumerable, "ListId", "Name", Model.ListId)) %>
<%: Html.Label("TextBox") %>
<%: Html.TextBoxFor(model => model.TextBox) %>
<%: Html.ValidationMessageFor(model => model.TextBox) %>
For this you need to write some JavaScript.
handle the onchange event for dropdown
<%: Html.DropDownList("ListId", new SelectList(ViewData["Lists"] as IEnumerable, "ListId", "Name", Model.ListId), new {#onchange="setVal(this)"}) %>
on your view
inside head block
<script type="text/javascript">
function setVal(obj)
{
document.getElementById("TextBox").value=obj.value;
}
</script>
I'm new in MVC2, so sorry for stupid question. I looked for nice answer, but can't find it. So my question is:
I have view:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MyProject.MyDB.MyProducts>>" %>
<%# Import Namespace="MyProject.MyDB" %>
<asp:Content ID="Content1" ContentPlaceHolderID="Content" runat="server">
<% using (Html.BeginForm())
{%>
<table>
<%
foreach (var item in Model)
{%>
<tr>
<td>
<%:item.name%>
</td>
<td>
<%:String.Format("{0:g}", item.date)%>
</td>
</tr>
<% } %>
</table>
<div>
<%:Html.TextArea("MyTextArea")%>
</div>
<p>
<input type="submit" value="Send" />
</p>
<% } %>
</asp:Content>
My controller is:
[HttpGet]
public ActionResult ViewMyProducts(int id)
{
List<MyProducts> myModel = GetMyProducts(id);
return View(myModel);
}
[HttpPost]
public ActionResult ViewMyProducts(/*???What should I put here???*/)
{
if(/*I want "MyTextArea" value here*/ == something && myModel/*from view*/.count==5}
{
//do something
}
return View(myModel);
}
So, in HttpPost I need myModel from view and value of "MyTextArea" from view. How can I get them?? I'll appreciate any help.
I would think that the following should work:
[HttpPost]
public ActionResult ViewMyProducts(string MyTextArea)
A helpful thing to do would be to explicitly call your Action in your Form - by changing this line:
<% using (Html.BeginForm())
to
<% using (Html.BeginForm("ViewMyProducts","ControllerName",HttpMethod.Post))
to ensure that the Submit action redirects it to the right Action.
As far as the model is concerned:
If you are just checking the Count - you could make a hidden field that returns the number of items in the "Model" like such:
<%: Html.Hidden("modelCount", Model.Count());
but if you want the entire Model - it would be need to be something like this:
<%: Html.Hidden("myModel", Model);
then you could further modify your Action to look something like this:
ViewMyProducts(string MyTextArea, int modelCount)
{
//...
}
or
ViewMyProducts(string MyTextArea, IEnumerable<MyProject.MyDB.MyProducts> myModel)
{
//...
}
Although you have access inside of the Controller to refresh the Model - so if you didn't need to pass back the entire thing you could still repopulate your view with a fresh call.
string myTextArea - or you could just check the FormCollection (I would recommend the named variable).
If you want to get the model back from the view, you will need to serialize it out as well in order to get back the values. If this is the case, I would convert the whole thing to a view model that either derives from your Model or has a public property that is your model, add a property for MyTextArea and then emit hidden input's for you model, named for the appropriate properties. Assuming that your model is persisted somewhere (database), I would just pass the key (id) and rehydrate the object from within the action result.
[HttpPost]
public ActionResult ViewMyProducts(ViewMyProductsViewModel viewModel)
{
if(viewModel.MyTextArea == "something" && (IEnumerable<foo>)myModel).Count()==5)) {
var model = repo.Get(myModel.First().Id);
// do something with the model
}
return View(viewModel);
}
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MyProject.MyDB.MyProducts>>" %>
<%# Import Namespace="MyProject.MyDB" %>
<asp:Content ID="Content1" ContentPlaceHolderID="Content" runat="server">
<% using (Html.BeginForm())
{%>
<table>
<%
foreach (var item in Model)
{%>
<tr>
<td>
<input type="hidden" name="viewModel.Id" value="<%:item.id%>" />
<%:item.name%>
</td>
<td>
<%:String.Format("{0:g}", item.date)%>
</td>
</tr>
<% } %>
</table>
<div>
<%:Html.TextArea("MyTextArea")%>
</div>
<p>
<input type="submit" value="Send" />
</p>
<% } %>
</asp:Content>
First of all You are rendering item.name and item.date as a text not html control. So You won't be able to receive it in controller method parameters.
I know you can do this
<%= Request.Form[0] %>
But how do you do something like this?
<% if(Request.Form[0]!=null)
echo "abc";
%>
<% if(Request.Form[0]!=null)
Response.Write("abc");
%>
Maybe you want to show the form value unless it doesn't exist then show "abc"?
<%= Request.Form[0] ?? "abc" %>
Or you could can use if blocks and normal markup inside.
<% if(Request.Form[0]!=null) { %>
<div class="echo">abc</div>
<% } %>