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 = "...")].
Related
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>
<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>
I try to show/hide a tinymce with radobutton. Like yes/no. So there are two radio buttons. yes - will show the tiny mce and no will hide the tinymce.
I have this:
showing tiny mce:
<div class="form-group">
#Html.Label(Resources.Entity.Product.PdfMessage, new { #class = "text-bold control-label col-md-2" })
<div class="col-lg-6 col-md-8 col-sm-10 ">
#Html.EditorFor(model => mailModel.PdfMessage, new { htmlAttributes = new { #class = "form-control tiny-mce", data_lang = System.Globalization.CultureInfo.CurrentUICulture.Name, id = "tinyMCE" } })
#Html.ValidationMessageFor(model => mailModel.PdfMessage)
#*#Html.TextArea("MailProductHandlers_message", mailModel.Message, new { #class = "form-control", #rows = 15 })*#
</div>
</div>
these are my radio buttons:
<div class="form-group">
#Html.Label(Resources.Entity.Product.GeneratePDF, new {#class = "text-bold control-label col-md-2" })
<div class="col-lg-6 col-md-8 col-sm-10 ">
#Html.Label(Resources.Entity.Product.GeneratePDFYes) #Html.RadioButtonFor(model => model.IsChecked, "Yes", new { #checked = true, id = "radioButton" })
#Html.Label(Resources.Entity.Product.GeneratePDFNo) #Html.RadioButtonFor(model => model.IsChecked, "No", new { #checked = true, id = "radioButton2" })
</div>
</div>
and this is my javascript:
<script>
$(document).ready(function () {
$("input[Id='radioButton']").click(function () {
if ($(this).is(':checked')) {
$('#tiny-mce').show();
}
else {
$('#tiny-mce').hide();
}
});
});
</script>
if I do this: $('#mceu_61').hide(); it hides the editor. but after I press on yes, it shows the editor. but if I then press No it doesnt hide anymore. And I have this:
#Html.EditorFor(model => mailModel.PdfMessage, new { htmlAttributes = new { #class = "form-control tiny-mce", #id = "mceu_61", data_lang = System.Globalization.CultureInfo.CurrentUICulture.Name } })
Your missing an #symbol for the id attribute:
Modify your script as well like this:
***EDIT some thing seems off about the radio buttons only one should be checked and they should have the same name **
you can use the # to denote and ID in Jquery by the way instead off looking it up by attribute
EDIT I changed a few things around, I don't think you need two individual ids I grouped them with a class, you should be able to check the on change event from that class instead of checking on both ids
#Html.EditorFor(model => mailModel.PdfMessage, new { htmlAttributes = new { #class = "form-control tiny-mce", #id = "tinyMCE", #data_lang = System.Globalization.CultureInfo.CurrentUICulture.Name } })
#Html.RadioButtonFor(model => model.IsChecked, "Yes", new { #checked = true, #class = "pdfchecker" })
// only one should be checked
#Html.RadioButtonFor(model => model.IsChecked, "No", new { #checked = false, #class = "pdfchecker" })
<script>
// this is short hand for document ready
$(function () {
//# is to denote an ID, . is to denote a class in jQuery the change function is hit when a radio button is change check the name to make sure they are apart of the same grouping
$(".pdfchecker").change(function () {
if ($(this).is(':checked')) {
$('#tiny-mce').show();
}
else {
$('#tiny-mce').hide();
}
});
</script>
I have a controller which gives a SelectList to a View which then renders multiple DropDownLists for a SelectList. I now want the DropDownLists to have different Values to be selected by Default. Is there any way of doing this?
Edit: Oh and of course the values I want to be defaults are available from my Model e.g. Model.Dj1_Id etc.
Controller:
[HttpGet]
public ActionResult EditPartyInfo(int ID)
{
Party prty = db.Partys.Find(ID);
ViewBag.People = new SelectList(db.People, "Id", "Name");
return View(prty);
}
View:
#model Musa.Models.Party
#using (Html.BeginForm("EditPartyInfo", "Events", FormMethod.Post))
{
#Html.AntiForgeryToken()
<!-- Some text input fields -->
<div class="form-group">
<label for="Dj1_Id">Dj 1</label>
<div class="form-inline">
#Html.DropDownList("Dj1_Id", ViewBag.People as SelectList, String.Empty, new { #class = "form-control person-select", style = "width: 50%;" })
</div>
</div>
<div class="form-group">
<label for="Dj2_Id">Dj 2</label>
<div class="form-inline">
#Html.DropDownList("Dj2_Id", ViewBag.People as SelectList, String.Empty, new { #class = "form-control person-select", style = "width: 50%;" })
</div>
</div>
<div class="form-group">
<label for="Dj3_Id">Dj 3</label>
<div class="form-inline">
#Html.DropDownList("Dj3_Id", ViewBag.People as SelectList, String.Empty, new { #class = "form-control person-select", style = "width: 50%;" })
</div>
</div>
<input type="submit" class="btn btn-primary" value="Los geht's" />
}
I Actually ended up doing:
Controller:
[HttpGet]
public ActionResult EditPartyInfo(int ID)
{
Party prty = db.Partys.Find(ID);
ViewBag.People = db.People;
return View(prty);
}
View:
/*...*/
#Html.DropDownList("Dj1_Id", new SelectList(ViewBag.People, "Id", "Name", Model.Dj1_Id), String.Empty, new { #class = "form-control person-select", style = "width: 50%;" })
/*...*/
#Html.DropDownList("Dj2_Id", new SelectList(ViewBag.People, "Id", "Name", Model.Dj2_Id), String.Empty, new { #class = "form-control person-select", style = "width: 50%;" })
/*...*/
#Html.DropDownList("Dj3_Id", new SelectList(ViewBag.People, "Id", "Name", Model.Dj3_Id), String.Empty, new { #class = "form-control person-select", style = "width: 50%;" })
Please try;
instead of
ViewBag.People as SelectList
this;
new SelectList(ViewBag.People, "Id", "Name", "Id value to select")
as second parameter of Html.DropDownLists
SelectList has a constructor where you can pass in the selected object, so:
new SelectList(db.People, "Id", "Name", db.People.FirstOrDefault(x => x.Id == party.Dj1_Id)
I personally prefer using IEnumerable<SelectListItem> like so:
ViewBag.People = db.People.Select(x => new SelectListItem { Text = x.Name, Value = x.Id, Selected = x.Id == party.Dj1_Id);
Either way should work.
My problem is:
I have two fields, and when i call my #Html.Actionlink method it send a null value for these two parameters.
This is my page code:
<div id="new-skill" class="row">
<label for="Description">Descreva brevemente a sua habilidade:</label>
#Html.TextBoxFor(model => model.skill.Description, new { #class = "form-control" })
<label for="Name">Em qual categoria ela está?</label>
#Html.TextBoxFor(model => model.skill.Category.Name, new { #class = "form-control" })
<div class="text-center margin-top15">
#Html.ActionLink("Adicionar nova habilidade", "InsertNewSkill", new
{
professionalId = ViewBag.professionalId,
skillDescription = "Test Text",
categoryName = Model.skill.Category.Name
}, new
{
#class = ""
})
</div>
</div>
This is my InsertNewSkill method:
public ActionResult InsertNewSkill(int professionalId, string skillDescription, string categoryName)
{
initBusinessObjects();
var professional = professionalBusiness.GetById(professionalId);
var newSkill = new SkillModel { Description = skillDescription, Category = new SkillCategoryModel { Name = categoryName } };
skillBusiness.Insert(newSkill);
professional.Skills.Add(newSkill);
professionalBusiness.Update(professional);
return View();
}
What I must to do to achieve this (send the textbox values)?
Have you tried adding the controllerName to your actionLink?
#Html.ActionLink("Adicionar nova habilidade", "InsertNewSkill","CONTROLLER_NAME", new
{
professionalId = ViewBag.professionalId,
skillDescription = "Test Text",
categoryName = Model.skill.Category.Name
}, new
{
#class = ""
})
Without using jQuery / javascript, you should use a form to get those values back to the server.
#{using(Html.BeginForm("InsertNewSkill", "ControllerName", FormMethod.Get)){
<div id="new-skill" class="row">
<label for="Description">Descreva brevemente a sua habilidade:</label>
#Html.TextBoxFor(model => model.skill.Description, new { #class = "form-control" })
<label for="Name">Em qual categoria ela está?</label>
#Html.TextBoxFor(model => model.skill.Category.Name, new { #class = "form-control" })
#Html.Hidden("professionalId", ViewBag.professionalId)
<div class="text-center margin-top15">
<input type="submit" value="Adicionar nova habilidade"/>
}}
With that said, typically you should POST these values back to the server and then redirect to a new ActionMethod (Thus, the acronym PRG for Post, Redirect, Get).