Join two fields with Linq query - c#

I am trying to show Name and Surname in a textbox with an autocomplete function, the problem is that I have these two fields in different columns in my Database (attached image)
I want to know if there is a way to concatenate these two variables so that the user can see in the Texbox the full name (v_Nombre + v_Apellido), since at present I only show the name
Any help for me?
View:
<script>
$(document).ready(function () {
$("#usuario").autocomplete({
source: '#Url.Action("BuscarUsuario")'
});
});
</script>
<div class="form-group">
<label>Usuario que retiro</label>
<input type="checkbox" name="checkusuario" id="idcheckusuario" checked="checked" value="true" />
#Html.TextBox("searchTerm", null, new { #class = "form-control", id = "usuario" })
</div>
My Controller:
public JsonResult BuscarUsuario(string term)
{
using (DataContext db = new DataContext())
{
List<string> resultado;
resultado = db.Usuarios.Where(x => x.v_Nombre.Contains(term)).Select(n => n.v_Nombre).Take(10).ToList();
return Json(resultado, JsonRequestBehavior.AllowGet);
}
}

You should be able to concatenate in your Select:
.Select(n => n.v_Nombre + " " + n.v_Apellido)

Related

ASP.Net Core 5 MVC Populate a drop down list with Database records

Title states what I'm trying to do.
Controller method:
public IActionResult Create()
{
IEnumerable<string> hList = from char s in _context.NR_Users select s.ToString();
List < NR_User > hUsers = new List<NR_User>();
hUsers = (from c in _context.NR_Users select c).ToList();
hUsers.Insert(0, new NR_User { ID = 0, Name = "Select" });
ViewBag.historyUsers = hUsers;
List<SelectListItem> options = new()
{
new SelectListItem { Value = "True", Text = "Yes" },
new SelectListItem { Value = "False", Text = "No" }
};
ViewBag.options = options;
return View();
}
View:
<div class="form-group col-md-4">
<label class="control-label">History PM</label>
<select asp-for="History_PM" name="History_PM" class="form-control" asp-items="#ViewBag.historyUsers"></select>
<span asp-validation-for="History_PM" class="text-danger"></span>
</div>
But when I run the app and navigate to the Create page I get this error:
RuntimeBinderException: Cannot implicitly convert type 'System.Collections.Generic.List<EnvApp.Models.DB.NR_User>' to 'System.Collections.Generic.IEnumerable<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>'. An explicit conversion exists (are you missing a cast?)
I understand that it can't implicitly convert the list to an IEnumerable, but how exactly do I do that?
You can convert the list using SelectList class.
Try replacing
<select asp-for="History_PM" name="History_PM" class="form-control" asp-items="#ViewBag.historyUsers"></select>
with
<select asp-for="History_PM" name="History_PM" class="form-control" asp-items="#(new SelectList(ViewBag.historyUsers, "ID", "Name"))"></select>

How Can I send selected text to controller from DropdownList

I want to send the selected text field in dropdown to the controller.
When I use the code as follows, I can send the id number to the controllers, but the value I selected in the list pass null.
In addition , if there is a registered value in the model, I want this field to be selected in the dropdownlist when the page is opened.
Controller
public ActionResult Degerlendir(int id ,string CV_STATU)
{
using (MULAKATDBEntities1 ent = new MULAKATDBEntities1())
{
CvViewModel cv = new CvViewModel();
var entData = ent.CV.FirstOrDefault(a => a.ID_CV == id);
entData.CV_STATU = CV_STATU;
ent.SaveChanges();
}
}
In View
#using (Html.BeginForm("Degerlendir", "Home", FormMethod.Post))
{
<input type="hidden" name="id" value="#Model.Cv.ID_CV" />
#Html.DropDownListFor(model => model.Cv.CV_STATU,
new List<SelectListItem> {
new SelectListItem() { Text = "Secilmedi" },
new SelectListItem() { Text = "Kabul edildi" },
new SelectListItem() { Text = "Reddedildi" } },
new {#id="cv_statu", #class = "form-control" })
<input type="submit" id="btnSubmit" value="KAYDET" class="btn btn-add" />
}
Set #name="cv_statu" within the HTML helper htmlAttributes for binding to parameters on POST like this.
Also change the controller method parameter to lowercase cv_statu. Only parameter names passed through URL routes are not case sensitive.
I am assuming that what you shared on your code for your ActionResult is already the HttpPost Action verb. There should be a proper HttpGet as well.
To solve your issue, make sure the first argument that you set on your DropDownListFor should match on the parameter of your Degerlendir
#Html.DropDownListFor(model => model.CV_STATU,
new List<SelectListItem> {
new SelectListItem() { Text = "Secilmedi", Value = "Secilmedi" },
new SelectListItem() { Text = "Kabul edildi", Value = "Secilmedi" },
new SelectListItem() { Text = "Reddedildi", Value = "Reddedildi", Selected = true} }, "Please select an option",
new {#id="cv_statu", #class = "form-control" })
As you notice, I changed your:
#Html.DropDownListFor(model => model.Cv.CV_STATU
To:
#Html.DropDownListFor(model => model.CV_STATU
Because what you set here will set the name attribute on your HTML. This will be binded on your parameter on your ActionResult of Degerlendir particularly your parameter:
string CV_STATU
Lastly, I added Value on your SelectListItem, because that will be passed on your ActionResult whatever you select on your DropDownList. To set the default selected value, just add Selected = true.

How can i create a SelectListItem() with Int Value

I have the folloiwng code inside my asp.net mvc action method:-
var CustomerData = customerlist.Select(m => new SelectListItem()
{
Text = m.SDOrganization.NAME,
Value = m.SDOrganization.ORG_ID.ToString(),
});
currently if i remove the ToString() from the ORG_ID , i will get an error that "can not explicitly convert long to string". so it seems that i have to define both the value and the text for the SelectListItem as strings. but since the SelectListItem should hold long , so is there a way to pass the values of the SelectListItem as long instead of strings?
...so is there a way to pass the values of the SelectListItem as long instead of strings?
No. And it doesn't make any sense to do so as when it is rendered, it's just HTML which has no concept of long.
If we have the action
public ActionResult Test()
{
var dictionary = new Dictionary<int, string>
{
{ 1, "One" },
{ 2, "Two" },
{ 3, "Three" }
};
ViewBag.SelectList = new SelectList(dictionary, "Key", "Value");
return this.View();
}
and the following view "Test.cshtml":
#using (Html.BeginForm())
{
#Html.DropDownList("id", ((SelectList)ViewBag.SelectList), "All")
<input type="submit" value="Go" />
}
The generated HTML is
<form action="/home/test" method="post">
<select id="id" name="id">
<option value="">All</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<input type="submit" value="Go">
</form>
and when we post to this action, text of your number is effectively parsed back into your desired type by the Model Binder
[HttpPost]
public ActionResult Test(int? id)
{
var selectedValue = id.HasValue ? id.ToString() : "All";
return Content(String.Format("You selected '{0}'", selectedValue));
}
And the above works as you might expect.

Why my drop down list items are invisible?

I am trying to make 2 cascading drop down lists.
First one works fine, you pick an item but when you go to the second drop down list, you can actually see correct number of spaces generating according to the items in the database but not the items themselves!
Its like they are invisible!
Can you please advise?
My View :
#using (Html.BeginForm("Browse", "Bookings", new { id = "TypeItemFormID", data_itemsListAction = #Url.Action("ItemsList") }))
{
<fieldset>
<legend> Type/Item</legend>
#Html.DropDownList("department", ViewBag.ItemTypesList as SelectList, "Select a Type", new {id="ItemTypeID"})
<div id="ItemsDivId">
<label for="Items">Items </label>
<select id="ItemsID" name="Items"></select>
</div>
<p>
<input type ="submit" value="Submit" id="SubmitID" />
</p>
</fieldset>
}
<script type="text/javascript">
$('#ItemTypeID').on('change', function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetItemTypeForm")',
data: { itemTypeId: $('#ItemTypeID').val() },
success: function (results) {
var options = $('#ItemsID');
options.empty();
options.append($('<option />').val(null).text("- Select an Item -"));
$.each(results, function () {
options.append($('<option />').val(this.ItemsID).text(this.Value));
});
}
});
});
</script>
My Controller :
[HttpPost]
public JsonResult GetItemTypeForm(string itemTypeId)
{
//pseudo code
var data = from s in db.Items
where s.ItemType.ItemTypeName == itemTypeId
select s.ItemName;
return Json(data);
}
You have the initial problem I mentioned in my comment, but it appears from your comments that your member names probably do not match either.
This may not be exact, as we do not know all your data/member names, but you may want something like this (using an anonymous type to return the shape of data you expect):
[HttpPost]
public JsonResult GetItemTypeForm(string itemTypeId)
{
//pseudo code
var data = from s in db.Items
where s.ItemType.ItemTypeName == itemTypeId
select new { Value = s.ItemName, ItemsID = s.ItemId };
return Json(data);
}

HTML: checkbox using c# razor & model

i have a checkbox that i'm using the model's company value to see if it should be checked.
company value can have more than one company as such: 1,9,10,15
in this case of multiple companies, following statement will never be true.
<input type=checkbox id=drsc class="comp" value="9" data-mini="true" #(Model.company=="9" ? "data-chkd=true" : "") />
so i'm trying to use logic below using the 'contains' clause and it doesn't seem to be working.
<input type=checkbox id=nn class="comp" value="9" data-mini="true" #((Model.company).Contains("9") ? "data-chkd=true" : "") />
if my company field has just company 9, first stmt is working. but not 2nd.
any thoughts?
UPD:
Try use razor syntax:
#Html.CheckBox("checkBoxName", Model.company == "9", new { id = "drsc", #class = "comp", value = "9", data_mini = "true" })
Result html code will be:
<input class="comp" data-mini="true" id="drsc" name="checkBoxName" type="checkbox" value="9">
if you have array of companies like this:
public class TmpModel
{
public IEnumerable<int> companies = new int[] { 1, 9, 10, 15 };
}
this code make checkbox checked if company 9 is one of model.companies
#Html.CheckBox("checkBoxName", Model.companies.Contains(9), new { id = "drsc", #class = "comp", value = "9", data_mini = "true" })

Categories