#Html.CheckBoxFor Set Value With Value From Model - asp.net-mvc

How do I set the value of this checkbox with the value of SelectedWebSite1URL property?
#model WLWeb.Models.MyModel
...
<label>#Html.CheckBoxFor(m => m.MyModel.SelectedWebSite1, new { #id = "chk1", #class = "chkWebSite", value = "HowDoIsetThis?" })#Html.DisplayFor(m => m.MyModel.SelectedWebSite1Name)</label>
model:
public class MyModel
{
...
public bool SelectedWebSite1 { get; set; }
public string SelectedWebSite1Name { get; set; }
public string SelectedWebSite1URL { get; set; }
}
Note: the reason I need this is to get the value (website url) with jquery:
$(function () {
$('#btnGoSite').click(function () {
$('.chkWebSite:checked').each(function () {
alert(this.value);
});
});
});

Just Remove MyModel
<label>#Html.CheckBoxFor(m => m.SelectedWebSite1, new { #id = "chk1", #class = "chkWebSite", value = "yourvaluehere?" })
#Html.DisplayFor(m => m.SelectedWebSite1Name)</label>

I think you are misunderstanding a checkbox. A checkbox is for boolean values (true or false) not strings.
It works for public bool SelectedWebSite1 { get; set; } but not for public string SelectedWebSite1URL { get; set; }
If you want to access SelectedWebSite1URL, render its value in hidden input and use something like (assumes the hidden input is immediately after the checkbox)
$(function () {
$('#btnGoSite').click(function () {
$('.chkWebSite:checked').each(function () {
alert($(this).next('input[type="hidden"]').val());
});
});
});

Try this
<label>
#Html.CheckBoxFor(x => x.SelectedWebSite1,new { #id = "chk1", #class = "chkWebSite"})
#Html.DisplayFor(m => m.MyModel.SelectedWebSite1Name)
</label>
No need to set value in html object attributes as check box will be automatically check/uncheck based on value of SelectedWebSite1 is true/false.

Related

Problem in showing ViewModel in Create form

I am learning how to use ViewModel to show the fields from 2 different models. I have one model containing the MsgTypeId, MsgType and MsgStatus and the another model OptStatus containing the StatusId, StatusName and StatusValue. The MsgStatus will be shown in form of drop down list and show all the values in OptStatus. Both models have a separate database table to store their values.
namespace theManager.Areas.Settings.Models
{
public class OptStatus
{
[Required]
[Key]
public int StatusId { get; set; }
[Required]
public string StatusName { get; set; }
[Required]
public char StatusValue { get; set; }
}
}
namespace theManager.Areas.Settings.Models
{
public class OptMsgType
{
[Required]
[Key]
public int MsgTypeId { get; set; }
[Required]
public string MsgType { get; set; }
[Required]
public string MsgStatus { get; set; }
}
}
I have created a ViewModel to show these fields in the Create form of OptMsgType. However, when I run the code, I got an error
"System.NullReferenceException: 'Object reference not set to an instance of an object.'"
I would like to ask if there is something wrong with my ViewModel. Thanks!
namespace theManager.Areas.Settings.ViewModels
{
public class OptMsgTypeCreateViewModel
{
public OptMsgType OptMsgType { get; set; }
public IEnumerable<SelectListItem> OptStatuses { get; set; }
}
}
OptMsgTypeController.cs
public IActionResult Create(int id)
{
var OptMsgTypeViewModel = new OptMsgTypeCreateViewModel();
OptMsgTypeViewModel.OptStatuses = _context.OptStatus.ToList().Select(x => new SelectListItem
{
Text = x.StatusName,
Value = x.StatusValue.ToString()
});
OptMsgTypeViewModel.OptMsgType = _context.OptMsgType.Where(a => a.MsgTypeId == id).FirstOrDefault();
//var v = _context.OptMsgType.Where(a => a.MsgTypeId == id).FirstOrDefault();
return View(OptMsgTypeViewModel);
}
I have problems in displaying the Create form which will show the fields declared in the ViewModel.
#model theManager.Areas.Settings.ViewModels.OptMsgTypeCreateViewModel
#{
ViewData["Title"] = "Create";
Layout = null;
}
<h2>Message Type Settings</h2>
#using (Html.BeginForm("Create","OptMsgType", FormMethod.Post, new { id= "popupForm" }))
{
if (Model != null && Model.OptMsgType.MsgTypeId > 0)
{
#Html.HiddenFor(a=>a.OptMsgType.MsgTypeId)
}
<div class="form-group">
<label>Message Type ID</label>
#Html.TextBoxFor(a=>a.OptMsgType.MsgTypeId,new { #class = "form-control" })
#Html.ValidationMessageFor(a=>a.OptMsgType.MsgTypeId)
</div>
<div class="form-group">
<label>Leave Type</label>
#Html.TextBoxFor(a => a.OptMsgType.MsgType, new { #class = "form-control" })
#Html.ValidationMessageFor(a => a.OptMsgType.MsgType)
</div>
<div class="form-group">
<label>Status</label>
#Html.DropDownListFor(model => model.OptStatuses, new SelectList(Model.OptStatuses, "Value", "Text"), htmlAttributes: new { #class = "form-control", id = "OptStatus" })
#Html.ValidationMessageFor(a => a.OptStatuses)
</div>
<div>
<input type="submit" value="Create" />
</div>
}
The System.NullReferenceException indicates that you are using a field without initializing it. It coulbe a problem with your view model or it could be a problem anywere else. For example from the code smaple is not possible to see where you initialize the context you are using to get the data, and that could be the cause of the exception you are getting.
Either way I would advise you to pay attention to yout IDE, it usualy indicates in which line adnd class the exception is being thown. If you navigate to that class at that line you will easily identify which field can be de cause of the exception.
Regarding your view model, its considered a good practice to always initialize the lists on your model on the constructor of your class. This way you can guarantee that they are already initialized when you try to use them.
So my sugestion would be to initialize your list on the constructor of your viewmodel
public OptMsgTypeCreateViewModel()
{
OptStatuses = new List<OptStatus>();
}
#George, thanks for the reply. Please try this then: instantiate your class in the viewmodel.
public class OptMsgTypeCreateViewModel
{
public OptMsgTypeCreateViewModel()
{
OptMsgType = new OptMsgType();
}
public OptMsgType OptMsgType { get; set; }
public IEnumerable<SelectListItem> OptStatuses { get; set; }
}
hi in action controller you should change this code:
OptMsgTypeViewModel.OptStatuses = _context.OptStatus.ToList().Select(x => new SelectListItem
{
Text = x.StatusName,
Value = x.StatusValue.ToString()
});
I think _context.OptStatus.ToList() in null so you get this exception. change code to this:
OptMsgTypeViewModel.OptStatuses =new list<SelectListItem>();
var temp= _context.OptStatus.ToList();
if(temp!=null&&temp.count()>0)
{
OptMsgTypeViewModel.OptStatuses = temp.Select(x => new SelectListItem
{
Text = x.StatusName,
Value = x.StatusValue.ToString()
}).tolist();
}
EDIT:
I think this object "Model.OptMsgType" is null
change code in view like this:
if (Model != null && Model.OptMsgType!=null && Model.OptMsgType.MsgTypeId > 0)
{
#Html.HiddenFor(a=>a.OptMsgType.MsgTypeId)
}

MVC Pass IDs from view to controller from checkbox multiselection

At the moment i have a table with a column fill with checkbox for each ID user. and i want to pass that value from checkbox checked from view to controller to perfom some action in actionresult CreatePlanning.
How can i do it ?
<td data-field="#Html.DisplayNameFor(model => model.Status_Coordinator)">
#Html.DisplayFor(model => item.Status_Coordinator)
<input id="Status_Coordinator" type="checkbox" name="Status_Coordinator" value="true" />
</td>
There are probably other ways to do this, but I have done it like this previously - Create a new Checkbox class like:
public class CheckboxModel
{
//Value of checkbox
public int Value { get; set; }
//description of checkbox
public string Text { get; set; }
//whether the checkbox is selected or not
public bool IsChecked { get; set; }
}
Initialise static list of users, to give you an idea (you probably have to generate it dynamically):
ListOfUserID = new List<CheckboxModel>
{
new CheckboxModel { Value = 1, Text = "User1" },
new CheckboxModel { Value = 2, Text = "User2" },
new CheckboxModel { Value = 3, Text = "User3" }
};
Use this class in the view (for example in a loop):
#Html.CheckBoxFor(m => Model.ListOfUserID[i].IsChecked)#Model.ListOfUserID[i].Text
#Html.HiddenFor(m => Model.ListOfUserID[i].Value)
#Html.HiddenFor(m => Model.ListOfUserID[i].Text)
Then you have the text or value of the checkbox in Controller action when the form is posted.
To select use Checkboxfor
`
Select your Order:
#foreach (var x in Model)
{
#Html.CheckBoxFor(modelItem => x.isSelected, new { #id="test"
,value = (x.Orderumber) })
}
Get Values
To pass value To the controller use JQuery as:
<script>
$(document).ready(function () {
$("#b1").click(function () {
var favorite = [];
$.each($("input[name='x.isSelected']:checked"), function () {
favorite.push($(this).val());
});
alert("Your order are: " + favorite.join(", "));
window.location.replace("https://localhost:44304/SecondPage/?
id="+favorite.join(", "));
});
});
</script>

How do I to get id of an enum value with #DropDownListFor?

I created an Enum and the values has id now I need to get the id in #Html.DropDownListFor but I don't know how to do it.
How could I get the id of Enum ?
Enum
public enum GainLosses
{
Gain = 1,
Loss = 2
};
Model
//Gain/Loss
[DisplayName("Gain/Loss")]
public int gainLoss { get; set; }
public IEnumerable<SelectListItem> gainLosses
{
get { return CustomEnum.Enum.GetItems<GainLosses>().Select(x => new SelectListItem() { Text = x.ToString(), Value = x.ToString() }); }
}
//
HTML
<div class="form-group">
<label for="#Html.IdFor(model => model.gainLoss)" class="cols-sm-2 control-label">Gain/Loss <img src="~/Imagens/required.png" height="6" width="6" title="requerido"></label>
#Html.DropDownListFor(model => model.gainLoss, Model.gainLosses, new { Class = "form-control" })
#Html.ValidationMessageFor(model => model.gainLoss, "", new { #class = "text-danger" })
</div><!--/Gain/Loss-->
I've already solved the problem.
[DisplayName("Gain/Loss")]
public int gainLoss { get; set; }
public IEnumerable<SelectListItem> gainLosses
{
get { return CustomEnum.Enum.GetItems<GainLosses>().Select(x => new SelectListItem() { Text = x.ToString(), Value = ((int)x).ToString() }); }
}
//

Working With ViewModels In Kendo UI ASP.net MVC

I have Three CaseCade Comboboxes, which work just fine for me
The problem is begins when I want to SAVE the id that Are Selected ,
I know how to get the Selected Id Which will be like this, and i have no problem with that
var countries = $("#countries").data("kendoDropDownList")
countries.value()
i don't know how to Set this values in my view model that i defined Above in My view, i don't know a way to pass view model to POST function.
This Is My View
#using System.Web.Optimization
#using Kendo.Mvc.UI
#model Mfr.Admin.Models.Address.CreateViewModel
#{
Layout = "~/Views/Shared/_Main.cshtml";
}
<
<div class="demo-section k-content">
<h4>Countries:</h4>
#(Html.Kendo().DropDownListFor(m=>m.CountryId)
.HtmlAttributes(new {style = "width:100%"})
.OptionLabel("Select Country...")
.DataTextField("Title")
.DataValueField("Id")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetCascadeCountries", "Address");
});
})
)
<h4 style="margin-top: 2em;">states:</h4>
#(Html.Kendo().DropDownListFor(m=>m.StateId)
.HtmlAttributes(new {style = "width:100%"})
.OptionLabel("Select state...")
.DataTextField("stateTitle")
.DataValueField("stateId")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetCascadeStates", "Address")
.Data("filterStates");
})
.ServerFiltering(true);
})
.Enable(false)
.AutoBind(false)
.CascadeFrom("CountryId")
)
<script>
function filterStates() {
return {
countries: $("#CountryId").val()
};
}
</script>
<h4 style="margin-top: 2em;">cities:</h4>
#(Html.Kendo().DropDownListFor(m=>m.CityId)
.HtmlAttributes(new {style = "width:100%"})
.OptionLabel("Select city...")
.DataTextField("cityTitle")
.DataValueField("cityId")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetCascadeCities", "Address")
.Data("filterCities");
})
.ServerFiltering(true);
})
.Enable(false)
.AutoBind(false)
.CascadeFrom("StateId")
)
<script>
function filterCities() {
return {
cities: $("#StateId").val()
};
}
</script>
<button class="k-button k-primary" id="get" style="margin-top: 2em; float: right;">Save</button>
</div>
<script>
$(document).ready(function () {
$("#get").click(function () {
// I want To call My post function Here, and pass viewmodel with initialized values to that
// I Suppose It will be something like this
//but I dont know how to set values to view model
//$.ajax({
// url: "#Html.Raw(Url.Action("Create", "Address"))",
// type: "POST",
// dataType: "json"
//)};
});
});
</script>
<style>
.k-readonly {
color: gray;
}
This is My save Action
address here is not initialized
[HttpPost]
public ActionResult Create(CreateViewModel address)
{
if (address == null)
throw new ArgumentNullException(nameof(address));
var addressModel = new Address()
{
Description = address.Description,
CityId = address.CityId,
StateId = address.StateId,
CountryId = address.CountryId,
UserApplicationId = User.Identity.GetUserId<int>()
};
_addressRepository.Add(addressModel);
_addressRepository.Complete();
return Json("");
}
this is view model
public class CreateViewModel
{
public int Id { get; set; }
public int UserApplicationId { get; set; }
public int CountryId { get; set; }
public int StateId { get; set; }
public int CityId { get; set; }
public string Description { get; set; }
}
You just need to send json back to controller
var countries = $("#countries").data("kendoDropDownList")
var countryId = countries.value();
var id = ..... //and so on
var data = {'Id': id, 'CountryId': countryId, /*ad so on*/ }
...
data: JSON.stringify(data)
...
Collect all data you need, put it in json object, stringify and if json properties correspond correctly to model properties, it will be automatically binded to controllers parameter.

Mvc3 DropdownlistFor error

I have a mvc3 dropdownlist containing Organization list.I am able to fill that using the code below.But when I submit the form, I am getting Id instead of name and the corresponding Id is null.
Controller
ViewBag.DropDownList =organizationModelList.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() });
return view();
Model
public class SubscriberModel
{
public OrgnizationList Organization { get; set; }
public RegisterModel RegisterModel { get; set; }
public SubscriberDetails SubscriberDetails { get; set; }
}
public class OrgnizationList
{
[Required]
public ObjectId Id { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Name")]
public string Name { get; set; }
}
View
#
model FleetTracker.WebUI.Models.SubscriberModel
#using (Html.BeginForm((string)ViewBag.FormAction, "Account")) {
<div>
#Html.DropDownListFor(m => m.Organization.Name, (IEnumerable<SelectListItem>)ViewBag.DropDownList, "---Select a value---")
</div>
}
When I change it tom => m.Organization.Id, then the modelstate will change to not valid.
Do you really need the name to be returned instead of the Id? If yes then instead of this:
ViewBag.DropDownList =organizationModelList.Select(x => new
SelectListItem { Text = x.Name, Value = x.Id.ToString() });
do this:
ViewBag.DropDownList =organizationModelList.Select(x => new SelectListItem { Text = x.Name, Value = x.Name });
Then remove the Required attribute for OrgnizationList.Id. If OrgnizationList is an entity, which I think it is, then you'll run yourself into trouble. I suggest you have a viewmodel that represents your input. So you don't have to deal with unnecessary required fields.
But what if the Name is not unique? Why can't you just accept the Id and save it in your data store? You are not modifying the name of OrgnizationList, I assume.
UPDATE:
If you really need both then tuck the Id on a hidden field:
Your controller method
ViewBag.DropDownList =organizationModelList.Select(x => new SelectListItem { Text = x.Name, Value = x.Id });
Your model
public class SubscriberModel
{
public int OrganizationId { get; set; }
// your other properties goeshere
}
Your view
<div>
#Html.HiddenFor(m=>m.OrganizationId)
#Html.DropDownListFor(m => m.Organization.Name, (IEnumerable<SelectListItem>)ViewBag.DropDownList, "---Select a value---")
</div>
and a bit of js needed...
$("Organization_Name").change(function(){
$("#OrganizationId").val($(this).val());
});
I did it using
$(document).ready(function () {
$("#DropDownList").change(function () {
$("#Organization_Id").val($(this).val());
$("#Organization_Name").val($("#DropDownList option:selected").text());
});
});
#Html.HiddenFor(m=>m.Organization.Id)
#Html.HiddenFor(m=>m.Organization.Name)
#Html.DropDownList("DropDownList", string.Empty)
controller
ViewBag.DropDownList = new SelectList(organizationModelList, "Id", "Name");

Resources