razor select box cannot convert lambda expression - razor

I need to convert this <select id="degreemultiselect" multiple="multiple"></select to a razor control #Html.DropDownList but I am getting the error message it says "cannot convert lambda expression to type string?" is that because of the model being a list public List<DegreeModel> selectedRequesterDegrees { get; set; } is there a work around for this?
#Html.DropDownList(x => x.selectedRequesterDegrees, new { id = "degreemultiselect", #class = "form-control" })
#Html.ValidationMessageFor(model => model.selectedRequesterDegrees)

Here is a working demo:
Model:
public class Test
{
public List<DegreeModel> selectedRequesterDegrees { get; set; }
}
View:
#model Test
#Html.DropDownListFor(x => x.selectedRequesterDegrees, new SelectList(Model.selectedRequesterDegrees, "Id", "Name"), null, new { id = "degreemultiselect", #class = "form-control" })
Controller:
[HttpGet]
public ActionResult Index()
{
var model = new Test()
{
selectedRequesterDegrees = new List<DegreeModel>()
{
new DegreeModel(){ Id=1,Name="aa"},
new DegreeModel(){ Id=2,Name="bb"},
new DegreeModel(){ Id=3,Name="cc"}
}
};
return View(model);
}
Result:

Related

DropDownListFor not selecting

I have a DropDownListFor that doesn't seem to be setting the expected Model property. Here's the HTML:
#using (Html.BeginForm())
{
#Html.DropDownListFor(x => x.SelectedItem,
new SelectList(Model.ItemList, "Id", "Desc"), null,
new { #class = "selected-list", #size = "3" });
<div>
#Model.SelectedItem
</div>
<input type="submit" value="Do Stuff"
asp-controller="My"
asp-action="DoStuff"
asp-route-itemId="#Model.SelectedItem" />
</div>
}
The div is just there for debugging purposes, and it either shows 0 or blank.
The underlying model has a property:
public int SelectedItem { get; set; }
I've also tried a string:
public string SelectedItem { get; set; } = String.Empty;
(Hence why 0 or blank)
The actual list itself displays fine, it just doesn't update the model on select. How can I get it to update the model?
If you use asp-route-itemId, your action need contains parameter named itemId to receive the value. But for your scenario, it seems to be useless to receive such value, because it will always receive the value you set instead of the dropdown changed value.
Here is a simple demo you could follow and check if any difference with yours:
Model
public class TestVM
{
public string SelectedItem { get; set; } = String.Empty;
public List<Item> ItemList { get; set; }
}
public class Item
{
public int Id { get; set; }
public string Desc { get; set; }
}
View(Index.cshtml)
#model TestVM
#using (Html.BeginForm())
{
#Html.DropDownListFor(x => x.SelectedItem,
new SelectList(Model.ItemList, "Id", "Desc"), null,
new { #class = "selected-list", #size = "3" });
<div>
#Model.SelectedItem
</div>
<input type="submit" value="Do Stuff"
asp-controller="Home"
asp-action="DoStuff" />
}
Controller
[HttpGet]
public IActionResult Index()
{
//Note: hard-coded the model just for easy testing.....
var model = new TestVM()
{
SelectedItem = "1",
ItemList = new List<Item>()
{
new Item(){Id=1,Desc="aa"},
new Item(){Id=2,Desc="bb"},
new Item(){Id=3,Desc="cc"}
}
};
return View(model);
}
[HttpPost]
public IActionResult DoStuff(TestVM model)
{
return View("index", model);
}
Result

ASP.NET MVC not passing select list

I have the following form:
#using (Html.BeginForm())
{
#Html.LabelFor(a => a.SomeText)
#Html.TextBoxFor(a => a.SomeText, new { #class = "form-control" })
#Html.ValidationMessageFor(a => a.SomeText)
<select name="ListOne" id="ListOne">
#foreach (var item in Model.ListOne)
{
<option value="#item.Id">#item.Name</option>
}
</select>
#Html.DropDownListFor(a => a.ListTwo, listTwo, null);
<input type="submit" value="Do Stuff" class="btn-primary"
asp-controller="My" asp-action="DoStuff"/>
. . .
}
On the server side, I have a simple controller method:
public async Task<IActionResult> DoStuff(MyViewModel myViewModel)
{
// ...
}
A breakpoint here shows that neither select list gets passed through, despite them both being visible in the HTML.
The VM looks like this:
public class MyViewModel
{
public string? SomeText { get; set; }
public SelectList? ListOne { get; set; } = new(new List<SelectListItem>());
public SelectList? ListTwo { get; set; } = new(new List<SelectListItem>());
}
ListOne and ListTwo are both null.
Please - could someone tell me why?

select dont save data on my database MVC/Json

I don't know why it don't save the AddressBookId form a select in my database
public class CreditCard
{
public int Id { get; set; }
[Display (Name="Customer")]
public int CustomerID { get; set; }
[Display(Name = "Billing Address")]
public int AddressBooKId { get; set; }
public virtual Customer Customer { get; set; }
}
Controller:
public ActionResult Create()
{
ViewBag.CustomerID = new SelectList(db.Customers, "Id", "FullName");
ViewBag.CCTypeId = new SelectList(db.CreditCardTypes, "Id", "CCName");
return View();
}
public JsonResult AddList(int Id)
{
var add = from a in db.AddressBooks
where a.CustomerId== Id
select a;
return Json(new SelectList(add.ToArray(), "AddressBookId", "Address"), JsonRequestBehavior.AllowGet);
}
public IList<AddressBook> Getadd(int CustomeId)
{
return db.AddressBooks.Where(m => m.CustomerId== CustomeId).ToList();}
Mi view
<div class="form-group">
#Html.LabelFor(model => model.AddressBooKId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<select id="AddressBooKId" name="AddressBooKId" class="form-control"> </select><br />
#Html.ValidationMessageFor(model => model.AddressBooKId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
Json
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/jscript">
$(function () {
$('#AddressBooKId').html(null)
$('#CustomerID').change(function () {
$.getJSON('/CreditCards/AddList/' + $('#CustomerID').val(), function (data) {
var items = '<option>Select a Address</option>';
$.each(data, function (i, add) {
items += "<option value='" + add.Value + "'>" + add.Text + "</option>"; });
$('#AddressBooKId').html(items);
}); }); });
</script>
Because your Dropdown is not bound with Model. You are creating it as independent control.
<select id="AddressBooKId" name="AddressBooKId" class="form-control"> </select>
Change the list Id and name to "AddressBookList". Create hidden field to keep the AddressBookId using model.
#Html.HiddenFor(m => m.AddressBooKId);
Change your JS code to update the new dropdown name.
Create a new change event handler for AddressBookList and set the value of HiddenField.
$('#AddressBookList').change(function () {
$('#AddressBooKId').val($('#AddressBookList').val());
}
Now when form will be submitted the Model property AddressBookId will have the selected value.

MVC5 DateTime field not call json on HTTPGET and not passed data on EditView to field

I have Birth Day field which check on Json if date is on the past.
it's working only for Edit not for Create
On Edit View- the data not passed to his field
My class include :
I have class:
[Required]
[DataType(DataType.Date)]
[Remote("ValidateBirthDate","Student")]
[DisplayFormat(ApplyFormatInEditMode = true)]
[DisplayName("Date Of Birth")]
public DateTime DateOfBirth { get; set; }
Create & Edit View: on Edit-the data not pass to the field
#Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { #class = "form-control" } })
Json on control:
//for Create
[HttpGet]
public JsonResult ValidateBirthDate(DateTime DateOfBirth)
{
int date = DateTime.Compare(DateOfBirth, DateTime.Today);
if(date>=0)
{
return Json("Please enter a valid date in the past", JsonRequestBehavior.AllowGet);
}
return Json(true,JsonRequestBehavior.AllowGet);
}
and for [HTTPPOST] -working fine:
//for Edit
[HttpPost]
[ActionName("ValidateBirthDate")]
public JsonResult ValidateBirthDatePost(DateTime DateOfBirth)
{....}
Why the data not passed to his field on Edit View?
Why its not response to Create too? What I miss?
(I try avoid datepicker..)
Solved by replacing:
public **string** DateOfBirth { get; set; }
Try the following:
1- Code to check the date value (HttpPost)
[HttpPost]
public JsonResult ValidateBirthDate(DateTime DateOfBirth)
{
int date = DateTime.Compare(DateOfBirth, DateTime.Today);
if(date>=0)
{
return Json("Please enter a valid date in the past", JsonRequestBehavior.AllowGet);
}
return Json(true,JsonRequestBehavior.AllowGet);
}
2- Html code
#Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DateOfBirth)

MVC4 Razor how to get selected value from dropdownlist?

My Model:
namespace mvc4deneme.Models
{
public class SiparisModel
{
public string SelectedValue { get; set; }
public IEnumerable<SelectListItem> Values { get; set; }
[Display(Name = "Ürün Tipi")]
public Material UrunTipi { get; set; }
[Display(Name = "Yüzey")]
public Material Yuzey { get; set; }
public class Material
{
//public int? ID { get; set; }
public string ID { get; set; }
public string Name { get; set; }
}
}
MY CONTROLLER:
//my control page is SiparisController
public class SiparisController : Controller
{
//
// GET: /Siparis/
public ActionResult Index()
{
DataTable dt = null;
Material material = null;
var model = new SiparisModel();
List<Material> lstYuzey = new List<Material>{
new Material { ID = null, Name = "Seçiniz" },
new Material { ID = "D/-", Name = "Tek Yüz" },
new Material { ID = "D/D", Name = "Çift Yüz" } };
ViewBag.Yuzey = lstYuzey;
List<Material> lstUrunTipi = new List<Material> {
new Material { ID = null, Name = "Seçiniz" },
new Material { ID = "3100140", Name = "MKYL" },
new Material { ID = "3100180", Name = "FS.MKYL FA" },
new Material { ID = "3100190", Name = "FS.MKYL FC" },
new Material { ID = "3100090", Name = "YL" }, };
ViewBag.UrunTipi = lstUrunTipi;
return View(model);
}
}
MY Index.cshtml view page:
#using (Html.BeginForm())
{
#Html.DropDownListFor(x => x.SelectedValue, Model.Values)
<button type="submit">OK</button>
#Html.LabelFor(m => m.UrunTipi)
#Html.DropDownListFor(m => m.UrunTipi.ID,
new SelectList(ViewBag.UrunTipi, "ID", "Name"),
new { style = "width:310px" })
#Html.ValidationMessageFor(m => m.UrunTipi.ID) }
#using (Html.BeginForm())
{
#Html.LabelFor(m => m.Yuzey)
#Html.DropDownListFor(m => m.Yuzey.ID,
new SelectList( ViewBag.Yuzey,"ID", "Name"),
new { style = "width:310px" })
#Html.ValidationMessageFor(m => m.Yuzey.ID)
}
My Ask:
How can i execute ok button to getting values of my UrunTipi and Yuzey selected values.
Thank you so much.
Regards,
B.Y.