How to get Selected Value in DropDownList from Database - asp.net-mvc

I want to get selected value in dropdownlist.
My View:
<div class="form-group">
#Html.LabelFor(model => model.AccountRefNo, "Account Desc", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("AccountRefNo", ViewBag.AccountRefNo as SelectList, "Account Desc", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.AccountRefNo)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PartyID, "Party Type", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("TypeID", ViewBag.TypeID as SelectList, "Party Type", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TypeID)
</div>
</div>
And, my Controller:
ViewBag.TypeID = new SelectList(db.PartyTypes, "TypeID", "TypeDesc", party.TypeID);
string[] codes = { "2.20.40.10", "3.50.10.20" };
ViewBag.AccountRefNo = new SelectList(db.ChartOfAccounts.Where(a => codes.Contains (a.AccountCode)), "AccountCode", "AccountDesc", party.AccountRefNo);
return View(party);
It seems it is OK but I don't know where the problem is. Both dropdownlists filling the lists but both are selecting their OptionLabel i.e selecting "Party Type" and "Account Desc" respectively.
Please help. Thanks!

This is in Edit controller and following worked.
string typeDescSelected = (from sub in db.PartyTypes
where sub.TypeID == party.TypeID
select sub.TypeDesc).First();
ViewBag.TypeDesc = new SelectList(db.PartyTypes, "TypeID", "TypeDesc", typeDescSelected);
string[] codes = { "2.20.40.10", "3.50.10.20" };
string accountDescSelected = (from sub in db.ChartOfAccounts
where sub.AccountCode == party.AccountRefNo
select sub.AccountDesc).First();
ViewBag.AccountDesc = new SelectList(db.ChartOfAccounts, "AccountCode", "AccountDesc", accountDescSelected);
return View(party);

SelectList constructors' first parameter needs to take a collection of SelectListItem:
Try the following and it should work provided there is data (void of null refs on PartyTypes and ChartOfAccounts:
ViewBag.TypeID = new SelectList
(
db.PartyTypes.Select(m=>new SelectListItem {Text=m.TypeDesc, Value=m.TypeID})
, "TypeID"
, "TypeDesc"
, party.TypeID
);
ViewBag.AccountRefNo = new SelectList
(
db.ChartOfAccounts
.Where(a => codes.Contains (a.AccountCode))
.Select(m=>new SelectListItem({Text=m.AccountDesc, Value=m.AccountCode}))
, "AccountCode"
, "AccountDesc"
, party.AccountRefNo //this maybe wrong
);
Also if ViewBag.AccountRefNo and party.AccountRefNo are the same type, then the last argument for the second SelectList constructor has to be incorrect. The argument should be the selected value so most likely party.AccountCode?

Related

DropdownListFor value not setting

I'm am dealing with a problem in Razor View. DropDown is working fine but the selected value is not setting properly. The value is set from the controller but in the view #Html.DropDownListFor value is not setting. Any help will be highly Appreciated. Thanks in Advance! Here is my Code.
View:
#Html.LabelFor(x => x.BranchID, htmlAttributes: new { #class = "col-2 col-form-label" })
<div class="col-md-3">
#Html.DropDownListFor(x => x.BranchID, new SelectList(Model.listofBranch, "BranchID", "BranchName"), new { #class = "form-control m-input", #id = "BranchID" })
#Html.ValidationMessageFor(model => model.BranchID, "", new { #class = "text-danger" })
</div>
Controller
mdlGRN.BranchID = obj.BranchID;
return View(mdlGRN);
In the view code the selected value is not specified, when you are calling:
#Html.DropDownListFor(x => x.BranchID,
new SelectList(Model.listofBranch, "BranchID", "BranchName"),
new { #class = "form-control m-input", #id = "BranchID" })
There is no value passed to the SelectList Constructor to indicate the SelectedValue
It should be something like this asuming that the value you want selected is the one saved into the model:
#Html.DropDownListFor(x => x.BranchID,
new SelectList(Model.listofBranch, "BranchID", "BranchName", Model.BranchID),
new { #class = "form-control m-input", #id = "BranchID" })

How to make #Html.EditorFor readonly depending on Drop List

I want to make #Html.EditorFor read only until a certain drop down selection is made. So my drop down looks like this:
List<SelectListItem> listDepartments = new List<SelectListItem>();
listDepartments.Add(new SelectListItem
{
Text = "Sales",
Value = "Sales"
});
listDepartments.Add(new SelectListItem
{
Text = "Staff",
Value = "Staff",
Selected = true
});
and I want to make the #Html.EditorFor read only unless the dropdown list is Staff. Is that hard to do?
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
You have to use Javascript to react to client browser events like a change of the entry selected in the dropdown. The following code uses jQuery to achieve this.
1) You will need a handle on the dropdown so you can listen to its change event. Here I use the #Html.IdFor() helper to get the Ids of the input elements that were generated by#Html.DropDownListFor()/ #Html.EditorFor(). Then I create jQuery selectors based on these Ids.
2) Register an JS event handler for the change event of the dropdown.
3) Toggle the readonly attribute of the text input depending on the value selected in the dropdown.
In your cshtml page:
<script type="text/javascript">
$(document).ready(function () {
// 1) get selectors
var dropDownSelector = $('##Html.IdFor(m => m.listDepartments)');
var textBoxSelector = $('##Html.IdFor(m => m.Description)');
// 2) listen to change event
dropDownSelector.on('change', function() {
// 3) toggle readonly attribute
var selectedValue = dropDownSelector.val();
if (selectedValue === 'Staff') {
textBoxSelector.removeAttr('readonly');
}
else {
textBoxSelector.attr('readonly', 'readonly');
// maybe you also want to clear the text input?
// textBoxSelector.val('');
}
});
});
</script>
How about something like below with a ternary operator ? ?
#{
var isReadonly = Model.Description == "Staff"
}
<div class="form-group">
#Html.LabelFor(model => model.Description, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, (isReadonly
? new { #class = "form-control", #readonly = "readonly" }
: new { #class = "form-control" }
))
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
I prefer to do my selects without a helper as I find them a bit clumsy so something like...
#{
var isReadonly = Model.Description == "Staff"
}
<div class="form-group">
#Html.LabelFor(model => model.Description, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<select name="Description" class="form-control #(isReadonly ? "readonly" : "")">
<option value="" selected="selected" disabled="disabled">Please select...</option>
#foreach (var option in Model.listDepartments)
{
<option value="#option.Value" #(option.Value == Model.Description ? "selected='selected'" : "")>#option.Text</option>
}
</select>
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>

MVC Saving field data from a view

I am using MVC and on my Index view I have placed a 'EditorFor' and a 'DropDownFor' fields on it for data entry. I would like a user to enter values and then 'Save' the record from the view. However I am having problems retrieving the data entered. I have tried creating an ActionResult and binding the data however nothing comes across. I have tried giving the fields id names and passing them in as parameters and again nothing is passed.
This is what I have in my View -
<h3>Sensitive Areas</h3>
#Html.HiddenFor(model => model.BurnSitesID, new { #id = "burnSitesID"})
<div class="form-group">
#Html.LabelFor(model => model.SensitiveTypesID, "Sensitive Area", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("SensitiveTypesID", string.Empty)
#Html.ValidationMessageFor(model => model.SensitiveTypesID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DistSensitiveArea, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DistSensitiveArea, new { #id = "distSensitiveArea" })
#Html.ValidationMessageFor(model => model.DistSensitiveArea, "", new { #class = "text-danger" })
</div>
<input type="submit" id="CreateArea" value="Save"/>
How would you take the values entered and pass them to the controller? I have tried a button however if my button is not named the exact same thing as the view it does not do anything.
Please use Html.BeginForm("ActionName","ControllerName", FormMethod.Post) .
Button should be Submit type .
If you are use textbox .
#Html.TextBoxFor("txtName", "", new { #class = "form-control", #maxlength = "50" })
<input type="submit" id="CreateArea" value="Save"/>
[HttpPost]
public ActionResult ActionName(FormCollection form)
{
string Name=form["txtName"].ToString();
}
Where Name is a name/ID of field name .
Thanks .

Cannot set cols in Asp.net MVC5 in TextAreaFor

I am using this code but cols=20 keeps getting HTMLed. I have seen other solutions but they do not seem to be using syntax like "new { htmlAttributes = new { etc". I am new to MVC and this syntax was generated by Scaffolding. I do not have the knowledge to change this syntax. I was hoping to just add ', cols = "34"' as per below.
<div class="form-group">
#Html.LabelFor(model => model.SpendDescription, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(model => model.SpendDescription, new { htmlAttributes = new { #class = "form-control", cols = "34" } })
#Html.ValidationMessageFor(model => model.SpendDescription, "", new { #class = "text-danger" })
</div>
</div>
The generated HTML is
<textarea id="SpendDescription" rows="2" name="SpendDescription" htmlattributes="{ class = form-control, cols = 34 }" data-val-maxlength-max="200" data-val-maxlength="Must be less than 200 characters." data-val="true" cols="20"></textarea>
Which is obviously wrong as "htmlattributes etc" became a string, 'form-control' did not become a class.
DARN! I just remembered that I changed the scaffolded code of EditorFor to TextAreaFor (a few days back) in order to have a text area. So I bet the code that passes htmlAttributes is wrong.
You have one too many levels of new {} :)
#Html.TextAreaFor(model => model.SpendDescription, new { #class = "form-control", cols = "34" })
should be sufficient.

MVC5 with EF6 : EditorFor() with an ICollection

I have a problem with my MVC5/EF6 website. I have a model like this :
(source: hostingpics.net)
When I'm creating an activity, I would like to add at least one date to it. So I created a new field in the form :
<div class="form-group">
#Html.LabelFor(model => model.Days, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Days)
#Html.ValidationMessageFor(model => model.Days)
</div>
</div>
According to various sources I've read here and there (https://stackoverflow.com/a/11403858/360708), I must create a file Day.cshtml in View/Shared/EditorTemplates/ so that I can tell MVC I want Day to have an editor for "day1" (DatePicker here).
This is because my model Day is an ICollection inside Activity, so I can't access the field day1 like this : "model.Days.day1". I've tried creating the Day.cshtml but it doesn't work. Here's the content of Day.cshtml
#model GAS_VS2013.Models.Day
#Html.EditorFor(o => o.day1)
Am I forgetting something or doing something wrong ?
Thanks
Thanks to Fals, it's now working with :
<div class="form-group">
#Html.LabelFor(model => model.Days, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Days, "Day")
#Html.ValidationMessageFor(model => model.Days)
</div>
</div>
To display the textbox as a HTML5 DatePicker, don't forget to add a DateTime.cshtml in the EditorTemplates with the following code (type of your day field must be DateTime) :
#model Nullable<DateTime>
#{
DateTime dt = DateTime.Now;
if (Model != null)
{
dt = (System.DateTime)Model;
}
#Html.TextBox("", String.Format("{0:d}", dt.ToShortDateString()), new { #class = "form-control datecontrol", type = "date" })
}
Source : http://www.aubrett.com/InformationTechnology/WebDevelopment/MVC/DatePickerMVC5.aspx(

Resources