Set selected drop down value from database in razor view MVC - c#

I am explicitly creating a dropdownlist in razor mvc view. I would like the default option to be one of the items, the value of that item should come from database
View Code
<div class="form-group">
#Html.LabelFor(model => model[i].Customer.HomeType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="SerivcesRegistrationInput col-md-10">
#Html.DropDownListFor(model => model[i].Customer.HomeType, new List<SelectListItem>
{
new SelectListItem{ Text="House", Value = "House",#(Model[i].CustomerServices.HomeType == "House" ? Selected = true : false) },
new SelectListItem{ Text="Apartment", Value = "Apartment" },
new SelectListItem{ Text="Farm", Value = "Farm" } },
"Select your home type", htmlAttributes: new { #class = "form-control" })
}
</div>
</div>
Controller Code
cs.HomeType = serviceDetails.HomeType;
sp.CustomerServices = cs;
return View("EditCustomerServices", ProviderList);
Model has the data I need but how can I set it to correct Dropdown list value. I tried using short hand if but it gives me an error
Invalid member initializer
Can I add if condition for Selected Boolean?

#{
var selected = Model.CustomerServices.HomeType == "House";
}
<div class="form-group">
#Html.LabelFor(model => model.Customer.HomeType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="SerivcesRegistrationInput col-md-10">
#Html.DropDownListFor(model => model.Customer.HomeType, new List<SelectListItem>
{
new SelectListItem{ Text="House", Value = "House", Selected = selected },
new SelectListItem{ Text="Apartment", Value = "Apartment" },
new SelectListItem{ Text="Farm", Value = "Farm" } },
"Select your home type", htmlAttributes: new { #class = "form-control" })
}
</div>
</div>

Related

System.InvalidOperationException on saving

When I fill in the information on my add product page and try to save, I get the error.
public ActionResult Create()
{
List<SelectListItem> values= (from i in db.Categories.ToList()
select new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString()
}
).ToList();
ViewBag.val = values;
return View();
}
View
<div class="form-group">
#Html.LabelFor(model => model.CategoryId, "CategoryId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m=> m.CategoryId ,(List<SelectListItem>)ViewBag.val, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CategoryId, "", new { #class = "text-danger" })
</div>
</div>
Error
System.InvalidOperationException: 'The ViewData item that has the key 'CategoryId' is of type 'System.Int32' but must be of type 'IEnumerable'.'
ViewBag doesn't require type-casting, try changing your code in View from
#Html.DropDownListFor(m=> m.CategoryId ,(List)ViewBag.val, new { #class = "form-control" })
to
#Html.DropDownListFor(m=> m.CategoryId ,#ViewBag.val, new { #class = "form-control" })
Or, you may also refer this SO answer
and use something like below -
#Html.DropDownListFor(m => m.ContribType,
new SelectList(#ViewBag.ContribTypeOptions, "ContribId",
"Value", Model.ContribTypeOptions.First().ContribId),
"Select, please")

Calling a controller Action Result method from view with an actionlink

I'm new to MVC and still figuring out how everything works. Currently, I am trying to call a method that is in my controller from my view but I'm not sure the best way to go about this. Here is my SalesOrdersController method that I want to run.
public ActionResult revertToPending(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
SalesOrder salesOrder = db.SalesOrders.Find(id);
if (salesOrder == null)
{
return HttpNotFound();
}
ViewBag.statusList = new List<Object>
{
new {value = SOStatus.Pending, text = "Pending" },
new {value = SOStatus.Released, text = "Released" },
new {value = SOStatus.Released, text = "Shipped" },
new {value = SOStatus.BackOrdered, text = "Back Ordered" },
new {value = SOStatus.Cancelled, text = "Cancelled" },
};
return View(salesOrder);
}
Here is my view
<div class="form-group">
#Html.LabelFor(model => model.SalesOrderStatus, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SalesOrderStatus, new SelectList(ViewBag.statusList, "value", "text"), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SalesOrderStatus, "", new { #class = "text-danger" })
#Html.ActionLink("Revert to Pending", "revertToPending", "SalesOrder")
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BillingStatus, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EnumDropDownListFor(model => model.BillingStatus, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.BillingStatus, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Details, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(model => model.Details, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Details, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn" />
</div>
</div>
And I want that to run when the user presses a button from the view.
So something like this
#Html.ActionLink("Revert to Pending", "revertToPending", "SalesOrder" )
I know that I'm doing it wrong as I don't want it to lead to the revertToPending View as it doesn't exist. But I want that controller method to run when the link is pressed.
Thanks

How to get fieldname from SQL Server DB using the field ID

In my views, I have a few drop-down lists that I use to get the ID and show the value to the user so they know what they are choosing. But in the view that I use to list everything that has already been added, it shows the chosen ID, but I want the name to appear
I tried this but it always shows the status that has the ID 1, which is the status "Active"
#Html.DropDownListFor(modelItem => item.status,
(SelectList)ViewBag.listStatus,
new { #class disabled = "" })
//controller
{
public ActionResult listStatus()
{
var list= ListsDAO.listStatus();
return View(list);
}
}
//DAO
{
public static IEnumerable<LISTS> listStatus()
{
using (var ctx = new PadraoEntities())
{
var result= from lists in ctx.LISTS
where lists.TYPE_LIST== "STATUS"
select new
{
lists.IDE_LIST,
lists.DES_LIST,
lists.VLR_LIST
};
var list= new List<LISTS>();
foreach (var item in result)
{
list.Add(new LISTS()
{
IDE_LIST = item.IDE_LIST,
VLR_LIST = item.VLR_LIST,
DES_LIST = item.DES_LIST
});
}
return list;
}
}
}
//view add
<div class="form-group">
#Html.LabelFor(model => model.status, htmlAttributes: new { #class = "control -Label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.status(SelectList)ViewBag.listStatus, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.status, "", new { #class = "text-danger" })
</div>
</div>
//view list
{
#Html.DropDownListFor(modelItem => item.ststus,(SelectList)ViewBag.listStatus,new { disabled = "" })
}
when listing id 1, I expected "active" to appear, id 2 shows "inactive", etc
Try this //controller
public ActionResult listStatus()
{
ViewBag.Status = new SelectList(//Code to get id and its property, "StatusId", "Status");
var list= ListsDAO.listStatus();
return View(list);
}
//View
<div class="form-group">
#Html.LabelFor(model => model.Status, "TaskId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Status", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Status, "", new { #class = "text-danger" })
</div>
</div>

Create function not saving data to database

I'm trying to get the create function to have the user selected values entered into the database. When the create button is pushed, no error is thrown but, the data is not populated. I'm pretty sure my frequency fields are causing the issue but have been unable to come with a solution.
There are two different types of frequencies a user can select depending upon their "Notification Name" selection. One selection has 3 separate fields for a numerical value, time frame (week, month etc.), and a before/after selection. The other simply states instantaneous as a static text field. Regardless of which option is chosen the frequency data should be populated into one cell within the database which is then separated using piping where necessary. I'm still pretty new to C# MVC so any help is greatly appreciated.
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,notificationType1,recipientTypeId,frequency")] NotificationType notificationType)
{
if (ModelState.IsValid)
{
db.NotificationType.Add(notificationType);
db.SaveChanges();
return RedirectToAction("Create");
}
ViewBag.recipientTypeId = new SelectList(db.RecipientType, "Id", "recipientRole", notificationType.recipientTypeId);
return View(notificationType);
}
View
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.notificationType1, "Notification Name", htmlAttributes: new { #class = "control-label col-md-2 helper-format" })
<div class="col-md-10" id="type_selection">
#Html.DropDownList("notificationType1", new List<SelectListItem> {
new SelectListItem { Text = "Make a Selection", Value="" },
new SelectListItem { Text = "Incomplete Documents", Value= "Incomplete Documents" },
new SelectListItem { Text = "All Documents Complete", Value = "All Documents Complete" },
new SelectListItem { Text = "Documents Requiring Action", Value = "Documents Requiring Action" }
}, new { #class = "helper-format", #id = "value_select", style = "font-family: 'Roboto', Sans Serif;" })
#Html.ValidationMessageFor(model => model.notificationType1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" id="frequency_group">
#Html.LabelFor(model => model.frequency, "Frequency", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-sm-3" id="frequency_group">
#Html.TextBoxFor(model => model.frequency, new { #class = "textbox-width", #placeholder = "42" })
#Html.DropDownList("frequency", new List<SelectListItem>
{
new SelectListItem { Text = "Day(s)", Value= "| Day"},
new SelectListItem { Text = "Week(s)", Value= "| Week"},
new SelectListItem { Text = "Month(s)", Value= "| Month"}
})
#Html.DropDownList("frequency", new List<SelectListItem>
{
new SelectListItem { Text = "Before", Value= "| Before"},
new SelectListItem { Text = "After", Value= "| After"}
})
</div>
<p class="col-sm-2" id="psdatetext">The Beginning</p>
</div>
<div class="form-group" id="freq_instant">
#Html.LabelFor(model => model.frequency, "Frequency", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="instant_text">
<p>Instantaneous</p></div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.recipientTypeId, "Notification For", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("recipientTypeId", new List<SelectListItem>
{
new SelectListItem { Text = "Me", Value= "Me"},
new SelectListItem { Text = "Account Manager", Value="Account Manager" },
new SelectListItem { Text = "Candidate", Value= "Candidate"},
new SelectListItem { Text = "Recruiter", Value="Recruiter" },
new SelectListItem { Text = "Manager", Value= "Manager"}
})
</div>
</div>
<div class="form-group">
<div class="col-md-offset-1 col-md-10">
<div id="hovercreate">
<button type="submit" value="CREATE" class="btn btn-primary" id="createbtn">CREATE</button>
</div>
</div>
</div>
</div>
}
JS for frequency options
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(document).ready(function () {
$('#frequency_group').hide()
$('#freq_instant').hide()
$('#value_select').change(function () {
var selection = $('#value_select').val();
$('#frequency_group').hide();
switch (selection) {
case 'Incomplete Documents':
$('#frequency_group').show();
break;
case 'All Documents Complete':
$('#frequency_group').show();
break;
}
});
$('#value_select').on('change', function () {
if (this.value == 'Documents Requiring Action') {
$("#freq_instant").show();
}
else {
$("#freq_instant").hide();
}
});
});
Have you placed a break-point on the method? And if so, is it triggering?
If not, try this...
From what I remember, all Controllers has a default parameter of ID which is set in the RouteConfig.cs file (App_Start/RouteConfig.cs).
There's a couple of ways to go from there.
1. Give the controller the ID parameter (e.g. (int ID))
2. Set the route value via the Route attribute
To do this you need to -
A. Add the following at the top of your RouteConfig.cs / RegisterRoutes method.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
//...
}
B. Add
[ValidateAntiForgeryToken]
[Route(#"Create/")]
public ActionResult Create([Bind(Include = ...
{
I would also suggest putting a break-point at the beginning of the method to see if its hitting it.
http://www.tutorialsteacher.com/mvc/routing-in-mvc
https://msdn.microsoft.com/en-us/library/system.web.mvc.routecollectionattributeroutingextensions.mapmvcattributeroutes%28v=vs.118%29.aspx
Is the Id key manually assigned? If not (for example, if it's an IDENTITY field), you shouldn't be binding it - remove Id from [Bind(Include = "...")].

ASP.NET Razor page dropdown list

<div class="form-group">
#Html.LabelFor(model => model.CountyId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CountyId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CountyId, "", new { #class = "text-danger" })
</div>
</div>
So I have the following code on my website. What I want to do is instead of having a text field where you type the countyID I would like to have the county name dropdown list where the user selects it by name and it would still register as a number. (For example instead of writing "1" he would just click and choose County1 from a list I make)
Edit:
Alright now I have this code
#Html.DropDownList("Counties", new List<SelectListItem>
{
new SelectListItem {Text = "Alba", Value = "1", Selected = true },
new SelectListItem {Text = "Arad", Value = "2" },
new SelectListItem {Text = "Arges", Value = "3" },
new SelectListItem {Text = "Bacau", Value = "4" },
}, "Select County")
#Html.EditorFor(model => model.CountyId, new { htmlAttributes = new { #class = "form-control" } })
How do I write it to replace the #Html.EditorFor(model => model.CountyId with the DropDownList selection?
Edit2: how do I use #Html.DropDownListFor ?
Buda, please try below
<div class="form-group">
#Html.LabelFor(model => model.CountyId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.CountyId, new List<SelectListItem>
{
new SelectListItem {Text = "Alba", Value = "1", Selected = true },
new SelectListItem {Text = "Arad", Value = "2" },
new SelectListItem {Text = "Arges", Value = "3" },
new SelectListItem {Text = "Bacau", Value = "4" },
}, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CountyId, "", new { #class = "text-danger" })
</div>
</div>
You can use the Html.DropDownListFor helper method
Add a new property to your view model to store the dropdown options. This property should be of type List
public class CreateUser
{
public int CountryId {set;get;}
public List<SelectListItem> Countries {set;get;}
}
Now in your GET action, populate the Countries collection property value on this view model object.
public ActionResult Create()
{
var vm = new CreateUser();
vm.Countries = new List<SelectListItem> {
new SelectListItem { Value="1", Text="USA" },
new SelectListItem { Value="2", Text="Canada" },
new SelectListItem { Value="3", Text="Mexico" }
};
return View(Vm);
}
And in your view
#model CreateUser
#using(Html.BeginForm())
{
<label>Select country</label>
#Html.DropDownListFor(s=>s.CountryId,Model.Countries,"Select one")
<input type="submit" />
}
Buda,
Probably you need to use the DropDownListFor html helper.
Please check the following answer to see if it clarifies your question
ASP.NET MVC + Populate dropdownlist
There are so many ways to do this, you can use this :
<div class="form-group col-4">
<label for="issueinput6">category</label>
<select id="issueinput6" class="form-control" data-toggle="tooltip" data-trigger="hover" data-placement="top"
data-title="Status">
#foreach (var item in ViewData["Categoryes"] as IList<AirPortModel.Models.Category>)
{
<option value="#item.Id">#item.CategoryName</option>
}
</select>
</div>
This way, you have all the information you want as a drop down.
These codes are from my project but you can change the names to use it for your own.
Also, you can use this pic of code to solve your problem.
<select data-val="true" data-val-required="The Category field is required." id="category" name="1">
<option value="">Pick one</option>
<option selected="selected" value="0">blabla</option>
<option value="1">blabla</option>
<option value="2">blabla</option>
<option value="3">blabla</option>
<option value="4">blabla</option>
<option value="5">blabla</option>
<option value="6">blabla</option>

Categories