Condition based rendering in asp.net MVC 3.0 - asp.net-mvc

I have a page which has 'n' number of panels and each panel need to be rendered based on certain condition and then the panel content as well rendered based on condition.
The page design can be shown below.
http://www.imageupload.co.uk/images/2014/08/08/PanelArrangment.png
I have to add too much of if statement which makes my code ugly.
<div class="panel-body clearfix">
<% if (/* some condtion */)
{ %>
<divclass="PanelGroup clearfix">
<label>
Name
</label>
<div class="field_area">
<%=Html.ComplexComponent()%>
</div>
</div>
<% }%>
<label>
Duration
</label>
<% if (/* some condtion */)
<div class="PanelGroup clearfix">
<label>
Time
</label>
<div class="field_area">
<%=Html.TextBox("Time", "", new { autocomplete = "off", maxlength =10, #class = "small" })%>
</div>
</adiv>
<% if (/* some condtion */)
<div class="PanelGroup clearfix">
<label>
DurationId
</label>
<div class="field_area">
<%=Html.TextBox("DurationId", "", new { autocomplete = "off", maxlength =10, #class = "small" })%>
</div>
</div>
<% }%>
After some changes I managed to reduce the condition by moving some of them to html helpers and below is my current code.
<%
using (Html.Panel())
{
using (var row = Html.PanelRow("Name"))
{
if(row.canShow) {
<%=Html.ComplexComponent()%>
}
}
%>
<label>
Panel
</label>
<%
using (var row = Html.PanelRow("Time"))
{
if(row.canShow) {
%>
<%=Html.TextBox("Time", "", new { autocomplete = "off", maxlength =10, #class = "small" })%>
<%
}}
using (var row = Html.PanelRow("Duration"))
{
if(row.canShow) {
%>
<%=Html.TextBox("Duration", "", new { autocomplete = "off", maxlength =10, #class = "small" })%>
<%
}}
}
%>
I am just wondering is there any better way than this to make my code better?
I am using ASP.Net MVC 3.0 with web forms and not possible to use Razor view.

Related

How to toggle Partial View on Single Submit Button in MVC?

Here is my Code
View
#using (Html.BeginForm("userrights", "Users", FormMethod.Post, new { #class = "form-horizontal", role = "form"}))
{
<div class="form-group">
<div class="col-md-7" style="padding-right:10px">
#Html.TextBoxFor(m => m.companyname, new { #class = "form-control", #placeholder = "Serach By Sponser Name" })
</div>
<div class="clearfix"></div>
</div>
<div class="form-group">
<div class="col-sm-2">
<button type="submit" id="btn_search" value="Search" name="btn_search" class="btn btn-default">Search</button>
</div>
<div class="clearfix"></div>
</div>
</div>
#Html.Partial("_userRightPartial", Model._UserRightPartialView)
<div class="clear"></div>
}
Controller Method
public ActionResult userrights()
{
IEnumerable<MenuListModel> _MenuListModel = _ftwCommonMethods.GetMenuItems();
IEnumerable<SubMenuListModel> _SubMenuListModel = _ftwCommonMethods.GetSubMenuItems("1");
UserRightViewSearch _UserRightViewSearch = new UserRightViewSearch();
UserRightPartialView _UserRightPartialView = new UserRightPartialView();
_UserRightPartialView._SubMenuListModel = _SubMenuListModel;
_UserRightViewSearch._UserRightPartialView = _UserRightPartialView;
_UserRightViewSearch._menu = _MenuListModel;
_UserRightViewSearch.selectedMenu = 0;
return View(_UserRightViewSearch);
}
I want when page first time loads, _userRightPartial partial view should be hidden. After Submitting By Search Button it should appear.
I know it can be possible by Hide and Show DIV. But i want is there other way to do it with MVC Code?

Using nested beginform in MVC

I have scenario where I have load data on dropdown selection change and after manipulation I have to submit the page for saving.
I have developed the page but since I new to MVC so can anyone verify me code and can suggest better approach of doing the same.
#using (Html.BeginForm("Save", "forecast"))
{
using (Html.BeginForm("YearChange", "forecast", FormMethod.Get, new {#id="frmYearChange" }))
{
<div class="span12">
<div class="well well-sm" style="padding-bottom: 0px !important;">
<div class="span5">
<div class="control-group">
<label class="control-label" for="selectGroup">
Select Group:</label>
<div class="controls">
#Html.DropDownListFor(m => m.groupId, Model.groupList, "--Select Group--", new { #id = "selectGroup" })
</div>
</div>
</div>
<div class="span5">
<div class="control-group">
<label class="control-label" for="selectYear">
Select Year:</label>
<div class="controls">
#Html.DropDownListFor(m => m.yearId, Model.yearList, "--Select Year--", new { #id = "selectYear", onchange = "selectYear_indexChanged();" })
</div>
</div>
</div>
<div class="clearfix">
</div>
</div>
</div>
}
.....
}
You can't have nested forms. You can however have multiple forms per view.
See W3C for more info.

how to retrieve data from database and show in dropdown in mvc

I want to retrieve data from database and show in dropdown. I used Model so i can take from model also. But it is not correctly retrieve. If In database 4 entries means it shows 4 dropdowns buttons but inside the dropdown there is no values. Can anyone help me out this problem?
My code in view
<div class="editor-label">
<%: Html.Label("Basic Qualification")%>
</div>
<div class="editor-field">
<div id="basic-qualification-container1" style="margin-bottom:4px;" class="basic-qualification-container left">
<% if (ViewData["BasicQualificationDegrees"]!=null){ %>
<% for (int i=0; i < Model.CandidateQualifications.Count();i++) {%>
<%: Html.DropDownList("BasicQualificationDegree1", new SelectList((IEnumerable<Dial4Jobz.Models.Degree>)ViewData["CandidateBasicQualifications"], "Id", "Name", (IEnumerable<int>)ViewData["BasicQualificationDegrees"]), new { #class = "qualification" })%>
<%: Html.TextBox("BasicQualificationSpecialization1", "", new { #title = "Enter basic qualification degree", #class="specialization" })%>
<%} %>
<%} else { %>
<select id="BasicQualificationDegree1" name="BasicQualificationDegrees"></select>
<%} %>
</div>
<div class="left">
<input type="button" id="btnAddBasicQualification" value="Add" />
<input type="button" id="btnDelBasicQualification" value="Remove" />
</div>
</div>
As per your question,
<% for (int i=0; i < Model.CandidateQualifications.Count();i++) {%>
what is this? why did you count the viewdata?
Code
<% if (ViewData["BasicQualificationDegrees"]!=null){ %>
<% var containerId = "basic-qualification-container" + i.ToString(); %>
<div id="<%: containerId %>" style="margin-bottom:4px;" class="basic-qualification-container left">
<%: Html.DropDownList("BasicQualificationDegree" + i.ToString(), new SelectList((IEnumerable<Dial4Jobz.Models.Degree>)ViewData["CandidateBasicQualifications"], "Id", "Name", basicQualifications.ElementAt(i-1).DegreeId), new { #class = "qualification" })%>
<%: Html.TextBox("BasicQualificationSpecialization" + i.ToString(), basicQualifications.ElementAt(i-1).Specialization, new { #title = "Enter basic qualification degree", #class = "specialization" })%>
</div>
<% } %>
<% } else { %>
<div id="basic-qualification-container1" style="margin-bottom:4px;" class="basic-qualification-container left">
<%: Html.DropDownList("BasicQualificationDegree1", new SelectList((IEnumerable<Dial4Jobz.Models.Degree>)ViewData["CandidateBasicQualifications"], "Id", "Name"), new { #class = "qualification" })%>
<%: Html.TextBox("BasicQualificationSpecialization1", "", new { #title = "Enter basic qualification degree", #class = "specialization" })%>
</div>
Hope It helps!.

ASP.NET MVC 3 validation problem

I have 2 or more forms with different one hidden value like:
<div class="comment-body">
<% using (Html.BeginForm(Model.ActionName, "Home", Model.RouteValues, FormMethod.Post, new { id = "FormAddComment", name = "FormAddComment" }))
{ %>
<% = Html.ValidationSummary(false) %>
<fieldset>
<% if (Model.CommentParentID != null)
{
htmlAttributes = new { placeholder = "Add a reply...", id = "Comment" };
postButtonTitle = "Post Reply";
%>
<input type="hidden" name="CommentParentID" id="CommentParentID" value="<% = Model.CommentParentID.ToString() %>" />
<%} %>
<% = Html.TextAreaFor(model => model.Comment, htmlAttributes)%>
<% = Html.ValidationMessageFor(model=>model.Comment) %>
<input type="submit" value="<% = postButtonTitle %>" class="small blue awesome noborder"
border="0" />
<% if (Model.CommentParentID != null)
{%>
<a class="hide-sub-comment" href="javascript:void(0);">Cancel</a>
<%} %>
</fieldset>
<%} %>
</div>
Problem is when I try to validate entered value I got the validator message twice. When I add text and click "post" again - one validator is hidden, but page is not valid yet. Why and how to solve it?
Thanks
Modifying answer since you changed the question.
You could do something like this
<script type="text/javascript">
$(document).ready(function () {
$("#NotHiddenComment").change(function () {
var temp = $("#NotHiddenComment").val();
$("#HiddenCommentID").text(temp);
});
});
</script>
This will make sure both fields have the same value so you do not get validation errors.

RadioButtonFor, EditorFor, xxxFor on Property passed into Partials

Many of the properties on my model need to be represented a simple group of Yes/No radio buttons. I need to check the corresponding radio button for pre-entered values. I went with a partial. Here's what I did:
RadioButtonsYesNo.ascx
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<KeyValuePair<string,string>>" %>
<div id="<%:Model.Key %>">
<%: Html.ValidationMessage(Model.Key)%>
<ul class='RadioButtonsYesNo'><li>
<%: Html.RadioButton(Model.Key, "Yes", Model.Value == "Yes", new { id = Model.Key + "_Yes" })%>
<label for='<%: Model.Key %>_Yes'>Yes</label>
</li><li>
<%: Html.RadioButton(Model.Key, "No", Model.Value == "No", new { id = Model.Key + "_No" })%>
<label for='<%: Model.Key %>_No'>No</label>
</li></ul>
</div>
Usage
<% Html.RenderPartial("RadioButtonsYesNo", new KeyValuePair<string, string> ("MyProp",Model.MyProp)); %>
Is there a best practice for passing in the property of interest and having RadioButtonFor render correctly?
Thanks.
Or in Razor:
#{
var yesRadioName = Model.Key + "_Yes";
var noRadioName = Model.Key + "_No";
#Html.RadioButtonFor(m => m.Key, true, new { #id = yesRadioName })
#Html.Label(yesRadioName , "Yes")
#Html.RadioButtonFor(m => m.Key, false, new { #id = noRadioName })
#Html.Label(noRadioName, "No")
}
Why not using RadioButtonFor in an editor template:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<% string name = ViewData.TemplateInfo.GetFullHtmlFieldId(""); %>
<div id="<%: name %>">
<%: Html.ValidationMessageFor(x => x) %>
<ul class="RadioButtonsYesNo">
<li>
<%: Html.RadioButtonFor(x => x, "Yes", new { id = name + "_Yes" }) %>
<label for="<%: name %>_Yes">Yes</label>
</li>
<li>
<%: Html.RadioButtonFor(x => x, "No", new { id = name + "_No" }) %>
<label for="<%: name %>_No">No</label>
</li>
</ul>
</div>
And then:
<%: Html.EditorFor(x => x.MyProp) %>

Resources