Add #Html.CheckBoxFor to email asp.net mvc 4 - asp.net-mvc

I have checkboxes in my feedback form, it looks like
I add checkboxes in my model
namespace CorePartners_Site2.Models
{
public class CareerForm
{
//...
public List<CheckBoxes> EmploymentType { get; set; }
}
public class CheckBoxes
{
public string Text { get; set; }
public bool Checked { get; set; }
}
}
add to my controller
[HttpGet]
public ActionResult CareerForm()
{
CareerForm model = new CareerForm();
model.EmploymentType = new List<CheckBoxes>
{
new CheckBoxes { Text = "Fulltime" },
new CheckBoxes { Text = "Partly" },
new CheckBoxes { Text = "Contract" }
};
return View(model);
}
but then I need to add selected checkboxes to email, but I dont know how to do it.
I tried
public ActionResult CareerForm(CareerForm Model, HttpPostedFileBase Resume)
{
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.BodyEncoding = Encoding.UTF8;
string message = //...
"Type: " + Model.EmploymentType;
msg.Body = message;
//....
}
but I get in my email just text Type: System.Collections.Generic.List`1[CheckBoxes]
How to make it work right?

something like following
string message = "Type: ";
foreach(var item in Model.EmploymentType)
{
if (item.Checked)
message += item.Text;
}

Your model.EmploymentType is a List<CheckBoxes>
model.EmploymentType = new List<CheckBoxes>
You will have to access it's value with index. You are converting to string
a System.Collection.Generic.

You will need to get a the text values from each checked checkbox in your list.
This is a list:
model.EmploymentType = new List<CheckBoxes>...
You want the checked ones:
var checked = model.EmploymentType.Where(x => x.Checked);
Then you want the Text property from those boxes:
string message = "Type: " + checked.Text;
Put this together inside your controller action and I'd expect it to look like this:
public ActionResult CareerForm(CareerForm Model, HttpPostedFileBase Resume)
{
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.BodyEncoding = Encoding.UTF8;
string message = "Type: ";
foreach(var box in Model.EmploymentType.Where(x => x.Checked)) {
message += box.Text + " ";
}
msg.Body = message;
}

Related

Placeholder on a #Html.Dropdownlist that is not selectable

How do i put a placeholder on my #Html.Dropdownlist that is not selectable.
I implemented chosen-jquery on my dropdown.
My code is as per below:
#Html.DropDownList("Id", new SelectList(new Ahib.Membership.UserFacade().GetAllUsers(), "Id", "Username"), "-select a system owner-", new { #class="chosen1-select" })
Currently my dropdownlist has a placeholder but the "-select a system owner-" becomes a selectable value which i dont want. How do solve this issue?
You can convert your list to the selectitem list and apply your disabled attribute from the controller itself.
like this
assuming your model is like this
class user
{
public int Id { get; set; }
public string Username { get; set; }
}
Convert your list to List<SelectListItem> like this, note here I am disabling the select a system owner entry.
public ActionResult Index()
{
List<user> users = new List<user>();
users.Add(new user { Id = 1, Username = "test1" });
users.Add(new user { Id = 2, Username = "test2" });
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "-select a system owner-", Value = "0", Disabled = true });
foreach (var item in users)
{
list.Add(new SelectListItem
{
Text = item.Username,
Value = item.Id.ToString()
});
}
ViewBag.listItems = list;
return View();
}
and in view use it like this
#Html.DropDownList("test", ViewBag.listItems as IEnumerable<SelectListItem>);
Result:

How to populate dropdown list for specific user?

I have three dropdown list:
#Html.DropDownListFor(m => m.Edit.SelectCountryId, Model.Edit.Countries, "Please select", new { id = "CountryID", #class = "form-control", #onchange = "LoadRegions();" })
#Html.DropDownListFor(m => m.Edit.SelectRegionId,Model.Edit.Region, "Please select", new { id = "RegionID", #class = "form-control", #onchange = "LoadCities();" })
#Html.DropDownListFor(m => m.Edit.SelectCityId, Model.Edit.City, "Please select", new { id = "CityID", #class = "form-control" })
I populate second one depending on first one and third depending on second...but when i want to display those dropdown lists for some specific user im able to display just countries
My model:
public int SelectCountryId { get; set; }
public int SelectRegionId { get; set; }
public int SelectCityId {get; set;}
public System.Web.Mvc.SelectList City { get; set; }
public System.Web.Mvc.SelectList Region{ get; set; }
public System.Web.Mvc.SelectList Country{ get; set; }
My controller:
model.Edit.SelectCountryId = user.ContactInformation.First().City.Region.Country.Id;
model.Edit.SelectRegionId = user.ContactInformation.First().City.Region.Id;
model.Edit.SelectCityId = user.ContactInformation.First().City.Id;
I get values on controller but i cant get display them in view
EDIT:
My scripts:
var region = $('#RegionID');
var urlCountries = "/Account/GetRegions";
$.getJSON(urlCountries, { countryId: $('#CountryID').val() }, function (response) {
// clear and add default (null) option
region.empty().append($('<option></option>').val('').text('Please select'));
for (var i = 0; i < response.length; i++) {
region.append($('<option></option>').val(response[i].Id).text(response[i].Name));
}
});
var city = $('#CityID');
var url = "/Account/GetCities"; // use the helper (dont hard code)
$.getJSON(url, { regionId: $('#RegionID').val() }, function (response) {
// clear and add default (null) option
city.empty().append($('<option></option>').val('').text('Please select'));
for (var i = 0; i < response.length; i++) {
city.append($('<option></option>').val(response[i].Id).text(response[i].Name));
}
});
My methods for GetCity() and GetRegions()
public IEnumerable<IRegion> GetRegions(int countryId)
{
Model.Administration.Region[] modelRegions = Model.Administration.Region.FindAll(DetachedCriteria.For<Model.Administration.Region>().Add(Restrictions.Eq("Country.Id", countryId)));
return modelRegions.Select(Region.ConvertFromModel).Cast<IRegion>().ToList();
}
public IEnumerable<ICity> GetCities(int regionId)
{
CityLimited[] modelCities = CityLimited.FindAll(DetachedCriteria.For<CityLimited>().Add(Restrictions.Eq("Region.Id", regionId)));
return modelCities.Select(City.ConvertFromModel).Cast<ICity>().ToList();
}
You need to pass an additional value indicating the selected option in the json data your returning to the view. Your GetRegions() method should look like
public JsonResult GetRegions(int countryId) // return a JsonResult
{
Model.Administration.Region[] modelRegions = Model.Administration.Region.FindAll(DetachedCriteria.For<Model.Administration.Region>().Add(Restrictions.Eq("Country.Id", countryId)));
var options = modelRegions.Select(Region.ConvertFromModel).Cast<IRegion>().ToList();
var selection = 1; // set the value of the selected option here - must match the `ID` property of one of one of the `IRegion` your returning
return Json(new { options = options, selection = selection }, JsonRequestBehavior.AllowGet);
}
Side note: Its not clear what modelRegions.Select(Region.ConvertFromModel).Cast<IRegion>().ToList(); returns but if IRegion contains more that just the ID and Name properties you need for the view, consider creating a collection of anonymous objects so you don't send unnecessary data across the wire
Then the corresponding script should be
var url = '#Url.Action("GetRegions", "Account")'; // use the helper (dont hard code)
var regions = $('#RegionID'); // cache the element
$('#CountryID').change(function() {
$.getJSON(url, { id: $(this).val() }, function(response) {
// clear and add default (null) option
regions.empty().append($('<option></option>').val('').text('Please select'));
$.each(response.options, function(index, item) {
cities.append($('<option></option>').val(item.Value).text(item.Text));
});
regions.val(response.selection); // set the selected value
});
});
and remove the #onchange = "LoadRegions(); from you markup
Ditto for the GetCities() controller method and the corresponding script

use enum display name in #html helper function

consider enum
public enum Education
{
[Display(Name="display for education 1")]
Education1,
[Display(Name="display for education 2")]
Education2,
[Display(Name="display for education 3")]
Education3,
}
Now, I'd like to have a drop down with the above display values
#Html.DropDownListFor(
model => model.Education,
new SelectList(#Enum.GetValues(typeof(Education)))
new {#class = "default"}
)
I would like to have the display name (and currently I get the enum string itself.
Someone knows how can I extract that in the .cshtml?
take a look at this
public static string[] GetEnumDisplays(Type type)
{
var displays = new List<string>();
foreach (FieldInfo f in type.GetFields(BindingFlags.Public | BindingFlags.Static))
{
object[] attr = f.GetCustomAttributes(typeof(DisplayAttribute), false);
if (attr.Length != 0)
{
var displayAttribute = (DisplayAttribute)attr[0];
displays.Add(displayAttribute.Name);
}
else
{
displays.Add(f.Name);
}
}
return displays.ToArray();
}

MVC checkboxes & FormCollection

On a mass-edit form page I display about 50 objects that have some boolean properties as well. The controller receives a FormCollection with all values from the edit page.
public void _EditAll(FormCollection c)
{
int i = 0;
if (ModelState.IsValid)
{
var arrId = c.GetValues("channel.ID");
var arrName = c.GetValues("channel.displayedName");
var arrCheckbox = c.GetValues("channel.isActive");
for (i = 0; i < arrId.Count(); i++)
{
Channel chan = db.Channels.Find(Convert.ToInt32(arrId[i]));
chan.displayedName = arrName[i];
chan.isActive = Convert.ToBoolean(arrCheckbox[i]);
db.Entry(chan).State = EntityState.Modified;
}
db.SaveChanges();
}
}
Now, for checkboxes, MVC creates hidden inputs on the form (otherwise "false" could not be posted back). In the controller, when receiving the FormCollection, this leads to the case that I receive an array of say
50 IDs,
50 names and ..
71 or so values for the checkboxes,
since the hidden checkbox has the same name as the visible one.
What's a good way to handle that and get the proper value of the checkbox?
Sample for editing array of entities that have boolean field.
Entity:
public class Entity
{
public int Id { get; set; }
public bool State { get; set; }
}
Controller:
public ActionResult Index()
{
Entity[] model = new Entity[]
{
new Entity() {Id = 1, State = true},
new Entity() {Id = 2, State = false},
new Entity() {Id = 3, State = true}
};
return View(model);
}
[HttpPost]
public ActionResult Index(Entity[] entities)
{
// here you can see populated model
throw new NotImplementedException();
}
View:
#model Entity[]
#{
using (Html.BeginForm())
{
for (int i = 0; i < Model.Count(); i++ )
{
#Html.Hidden("entities[" + i + "].Id", Model[i].Id)
#Html.CheckBox("entities[" + i + "].State", Model[i].State)
}
<input type="submit"/>
}
}
The only tricky thing is html elements naming.
More info about binding arrays.
I'm converting all arrays containing checkbox-values:
"false" => "false", if not preceded by "true"

More Elegant way to return json array to ASP.NET MVC

{Sorry new to JSON}
I need to build up an array of resources (Users) and pass it in to my view, might be a better way than what ive done below? (Demo)
My model is simply
public class ScheduleUsers
{
public string Resource{ get; set; }
}
On my controller
var users = new JsonArray(
new JsonObject(
new KeyValuePair<string,JsonValue>("id","1"),
new KeyValuePair<string,JsonValue>("name","User1")),
new JsonObject(
new KeyValuePair<string, JsonValue>("id", "2"),
new KeyValuePair<string, JsonValue>("name", "User2"))
);
model.Resources = users.ToString();
Why don't you just return a list of entities as a JSON result, like:
public class CarsController : Controller
{
public JsonResult GetCars()
{
List<Car> cars = new List<Car>();
// add cars to the cars collection
return this.Json(cars, JsonRequestBehavior.AllowGet);
}
}
It will be converted to JSON automatically.
I did this and this works
JavaScriptSerializer js = new JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
//Serialize
js.Serialize(GetResources(), sb);
public List<ScheduledResource> GetResources()
{
var res = new List<ScheduledResource>()
{
new ScheduledResource()
{
id = "1",
color = "blue",
name = "User 1"
},
new ScheduledResource()
{
id = "2",
color = "black",
name = "User 2"
},
};
return res;
}

Resources