how to retrieve data from database and show in dropdown in mvc - asp.net-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!.

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?

MVC 5 - Information in partial view is null after submit

I have a large form and it's becoming too big so I want to start using partial view to keep it cleaner.
Here is a little part of the form that shows the main contact and a list of alternative contacts. The user can add more contacts (the buttons shows a popup to insert new contact) and the user can change the contact from active to inactive (through the checkbox on the table). Right now this is working but like i said i want to be able to use a partial view for the table.
<div class="box box-primary">
<div class="box-header">
<h3 class="box-title">Contacts</h3>
</div>
<div class="box-body">
<div class="form-group">
<div class="col-xs-4">
<label>Phone:</label>
#Html.EditorFor(model => model.Persons.Phone, new { htmlAttributes = new { #class = "form-control", #id = "phone" } })
#Html.ValidationMessageFor(model => model.Persons.Phone, "", new { #class = "text-danger" })
</div>
<div class="col-xs-8">
<label>Email:</label>
#Html.EditorFor(model => model.Persons.Email, new { htmlAttributes = new { #id = "email", #class = "form-control", #placeholder = "Introduza o email..." } })
#Html.ValidationMessageFor(model => model.Persons.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<label>Address:</label>
#Html.TextAreaFor(model => model.Persons.Address, new { #class = "form-control", #placeholder = "Introduza a morada...", #rows = 3 })
#Html.ValidationMessageFor(model => model.Persons.Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
#if (Model.Contacts != null && Model.Contacts.Count > 0)
{
<table id="example2" class="table table-bordered table-hover dataTable" aria-describedby="example2_info">
<thead>
<tr role="row">
<th class="sorting_asc" role="columnheader" tabindex="0" aria-controls="example2" rowspan="1" colspan="1" aria-sort="ascending">Contact</th>
<th class="sorting" role="columnheader" tabindex="0" aria-controls="example2" rowspan="1" colspan="1">Contact Type</th>
<th class="sorting" role="columnheader" tabindex="0" aria-controls="example2" rowspan="1" colspan="1">Active</th>
</thead>
<tbody role="alert" aria-live="polite" aria-relevant="all">
#{
string cssClass = string.Empty;
string activo = string.Empty;
}
#for (var i = 0; i < Model.Contacts.Count; i++)
{
cssClass = i % 2 == 0 ? "even" : "odd";
<tr class="´#cssClass">
<td class=" ">#Html.DisplayFor(model => Model.Contacts[i].Contact)</td>
<td class=" ">#Html.DisplayFor(model => Model.Contacts[i].contacttypes.Name)</td>
<td class=" ">#Html.CheckBoxFor(model => Model.Contacts[i].IsActive, new { #class = "flat-green" })</td>
</tr>
#Html.HiddenFor(model => Model.Contacts[i].ContactsId)
}
</tbody>
</table>
}
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input type="button" value="Add New Contact" class="buttonCreate btn btn-primary btn-sm" />
</div>
</div>
</div>
So here is the same HTML using the partial view
<div class="box box-primary">
<div class="box-header">
<h3 class="box-title">Contacts</h3>
</div>
<div class="box-body">
<div class="form-group">
<div class="col-xs-4">
<label>Phone:</label>
#Html.EditorFor(model => model.Persons.Phone, new { htmlAttributes = new { #class = "form-control", #id = "phone" } })
#Html.ValidationMessageFor(model => model.Persons.Phone, "", new { #class = "text-danger" })
</div>
<div class="col-xs-8">
<label>Email:</label>
#Html.EditorFor(model => model.Persons.Email, new { htmlAttributes = new { #id = "email", #class = "form-control", #placeholder = "Introduza o email..." } })
#Html.ValidationMessageFor(model => model.Persons.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<label>Address:</label>
#Html.TextAreaFor(model => model.Persons.Address, new { #class = "form-control", #placeholder = "Introduza a morada...", #rows = 3 })
#Html.ValidationMessageFor(model => model.Persons.Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
#Html.Partial("ContactListControl", Model.Contacts)
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input type="button" value="Add New Contact" class="buttonCreate btn btn-primary btn-sm" />
</div>
</div>
</div>
and here is the Partial view:
#model List<RecruitmentWeb.Models.contacts>
<table id="example2" class="table table-bordered table-hover dataTable" aria-describedby="example2_info">
<thead>
<tr role="row">
<th class="sorting_asc" role="columnheader" tabindex="0" aria-controls="example2" rowspan="1" colspan="1" aria-sort="ascending">Contato</th>
<th class="sorting" role="columnheader" tabindex="0" aria-controls="example2" rowspan="1" colspan="1">Tipo de Contato</th>
<th class="sorting" role="columnheader" tabindex="0" aria-controls="example2" rowspan="1" colspan="1">Activo</th>
</thead>
<tbody role="alert" aria-live="polite" aria-relevant="all">
#{
string cssClass = string.Empty;
string activo = string.Empty;
}
#for (var i = 0; i < Model.Count; i++)
{
cssClass = i % 2 == 0 ? "even" : "odd";
<tr class="´#cssClass">
<td class=" ">#Html.DisplayFor(model => Model[i].Contact)</td>
<td class=" ">#Html.DisplayFor(model => Model[i].contacttypes.Name)</td>
<td class=" ">#Html.CheckBoxFor(model => Model[i].IsActive, new { #class = "flat-green" })</td>
</tr>
#Html.HiddenFor(model => Model[i].ContactsId)
}
</tbody>
The Problem
If the user changes a contact from active to inactive or vice-versa, when I submit the form the changes don't go through. In fact, the list is null and contains no information. It works if i don't use partial view.
So what I'm I missing?
You passing only a property of your model to the partial so the the hidden inputs you are generating have the name attribute name="[0].ContactsId", name="[1].ContactsId" etc. whereas they needs to be name="Contacts[0].ContactsId", name="Contacts[1].ContactsId" etc (ditto for the checkboxes).
Change the partial view model to the same as the main view (you haven't indicated what it is), and then pass the model as
#Html.Partial("ContactListControl", Model)
and adjust the Html helpers to suit. However I would recommend you consider using a custom EditorTemplate for RecruitmentWeb.Models.Contacts rather than a partial view for this.

Condition based rendering in asp.net MVC 3.0

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.

passing values from view to Controller N then to other View

Customer:
<p></p>
<p></p>
<div> <% foreach (var item in Model)
{ %>
You are viewing Users of Customer: <%:item.Customer %>
<%break; %>
<%} %></div>
<p></p>
<% Html.RenderPartial("EditUsers", Model); %>
<p>
<%: Html.ActionLink("Create New", "Create", "Profile", null, null)%>
</p>
Now i got to pass the <%:item.Customer %> through the %: Html.ActionLink("Create New", "Create", "Profile", null, null)%> and that should be displayed in the Create view
here is the Controller n i will give the Create view too
Controller:
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(string UserName, string Password, string FirstName, string LastName,
string MiddleInitial, string Email,string Telephone, bool IsAdmin, bool IsSubAdmin)
{
UserDAL userDALObject = new UserDAL();
tblUser newUser = new tblUser();
newUser.Customer = customerNumber;
newUser.UserName = UserName;
newUser.Password = Password;
newUser.FirstName = FirstName;
newUser.LastName = LastName;
newUser.MiddleInitial = MiddleInitial;
newUser.Email = Email;
newUser.Telephone = Telephone;
newUser.IsAdmin = IsAdmin;
newUser.IsSubAdmin = IsSubAdmin;
userDALObject.AddUserDetails(newUser);
TempData["UserCreationMsg"] = string.Format("User named :{0}, is created",UserName);
return View();
}
public ActionResult EditUser(string id)
{
UserDAL userDALObject = new UserDAL();
tblUser userDetails = userDALObject.GetUser(Int32.Parse(id));
TempData["EditUserId"] = id;
return View(userDetails);
}
the Create View
<%if(TempData["UserCreationMsg"] != null)%>
<%{ %>
<%: TempData["UserCreationMsg"].ToString() %>
<%} %>
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<div class="editor-label">
<%: Html.LabelFor(model => model.UserName) %>
</div>
<div class="editor-field">
<%: Html.TextBox("UserName") %>
<%: Html.ValidationMessageFor(model => model.UserName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Password) %>
</div>
<div class="editor-field">
<%: Html.Password("Password") %>
<%: Html.ValidationMessageFor(model => model.Password) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.FirstName) %>
</div>
<div class="editor-field">
<%: Html.TextBox("FirstName") %>
<%: Html.ValidationMessageFor(model => model.FirstName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.LastName) %>
</div>
<div class="editor-field">
<%: Html.TextBox("LastName") %>
<%: Html.ValidationMessageFor(model => model.LastName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.MiddleInitial) %>
</div>
<div class="editor-field">
<%: Html.TextBox("MiddleInitial") %>
<%: Html.ValidationMessageFor(model => model.MiddleInitial) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Email) %>
</div>
<div class="editor-field">
<%: Html.TextBox("Email") %>
<%: Html.ValidationMessageFor(model => model.Email) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Telephone) %>
</div>
<div class="editor-field">
<%: Html.TextBox("Telephone") %>
<%: Html.ValidationMessageFor(model => model.Telephone) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.IsAdmin) %>
</div>
<div class="editor-field">
<%: Html.CheckBox("IsAdmin") %>
<%: Html.ValidationMessageFor(model => model.IsAdmin) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.IsSubAdmin) %>
</div>
<div class="editor-field">
<%: Html.CheckBox("IsSubAdmin") %>
<%: Html.ValidationMessageFor(model => model.IsSubAdmin) %>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
What exactly is your issue?
On the side point, you should be using Model Binding to pass a person object to the CreateView action method rather than passing each property separately. It will reduce a lot of your code. Search Model Binding for more details.

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