I have a functional autocomplete, however when I fill in the data it shows me the name to select, but when I select it ... it stores the ID of that name that I selected.
In the database the value to save is the ID of that name selected, but is there any way it can fill me in with the name and store the ID in the database?
for example, I selected a name, but it shows me the ID and not the name, as shown in the image. Is it possible that he shows me the name and just keeps the ID?
Model
public partial class Filho
{
public int ID_Filho { get; set; }
public int ID_Utilizador { get; set; }
public string Nome { get; set; }
public string Morada { get; set; }
public System.DateTime DataNascimento { get; set; }
public System.DateTime DataRegisto { get; set; }
public int ID_Sala { get; set; }
public virtual Utilizador Utilizador { get; set; }
public virtual Sala Sala { get; set; }
}
Controller
public JsonResult AutoComplete(string prefix)
{
ClassEntities entities = new ClassEntities();
var pais = (from Utilizador in entities.Utilizador
where Utilizador.NomeUtilizador.StartsWith(prefix)
select new
{
label = Utilizador.NomeUtilizador,
val = Utilizador.ID_Utilizador
}).ToList();
return Json(pais);
}
HTML
<div class="wrap-input100 rs1-wrap-input100 validate-input">
<span class="label-input100">NAME</span>
<input class="input100" type="text" id="txtUtilizador" name="ID_Utilizador">
<span class="focus-input100"></span>
</div>
JavaScript
<script type="text/javascript">
$("#txtUtilizador").autocomplete({
source: function (request, response) {
$.ajax(
{
url: '/Filhos/AutoComplete/',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
cache: false,
success: function (data) {
response($.map(data, function (item) {
return {
label: item.label,
value: item.val,
};
}))
}
})
},
error: function (error) {
alert(error);
}
});
</script>
Method
public ActionResult Create()
{
ViewBag.ID_Utilizador = new SelectList(db.Utilizador, "ID_Utilizador", "NomeUtilizador");
ViewBag.ID_Sala = new SelectList(db.Sala, "ID_Sala", "NomeSala");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID_Filho,ID_Utilizador,Nome,Morada,DataNascimento,DataRegisto,ID_Sala")] Filho filho)
{
if (ModelState.IsValid)
{
db.Filho.Add(filho);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ID_Utilizador = new SelectList(db.Utilizador, "ID_Utilizador", "NomeUtilizador", filho.ID_Utilizador);
ViewBag.ID_Sala = new SelectList(db.Sala, "ID_Sala", "NomeSala", filho.ID_Sala);
return View(filho);
}
You need add a hidden field with name to keep value when submit form.
<input type="hidden" name="ID_Utilizador"/>
Implement select method, comment out custom mapping
select: function (event, ui) {
event.preventDefault();
$(this).val(ui.item.label);
$("[name='ID_Utilizador']").val(ui.item.value);
}
This is html for page
<div class="wrap-input100 rs1-wrap-input100 validate-input">
<span class="label-input100">NAME</span>
<input class="input100" type="text" id="txtUtilizador">
<input type="hidden" name="ID_Utilizador"/>
<span class="focus-input100"></span>
</div>
<script type="text/javascript">
$("#txtUtilizador").autocomplete({
source: function (request, response) {
$.ajax(
{
url: '/Filhos/AutoComplete/',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
cache: false,
success: function (data) {
//response($.map(data, function (item) {
// return {
// label: item.label,
// value: item.val,
// id : item.val
// };
//}))
response(data);
}
})
},
select: function (event, ui) {
event.preventDefault();
$(this).val(ui.item.label);
$("[name='ID_Utilizador']").val(ui.item.value);
},
error: function (error) {
alert(error);
}
});
Related
I send model with ajax on server with post request.
I have next model and a controller that has a method of fasting.
public class TestDto: BaseDto
{
[Required]
public ProductGalleryDto GalleryProduct { get; set; }
public int? RetailPriceEur { get; set; }
[Required]
public int? AmountSpc { get; set; }
public bool? PrizeSent { get; set; }
public string Comment { get; set; }
public DateTime? StartDate { get; set; }
[Required]
public DateTime? ExpirationDate { get; set; }
public bool IsParticipant { get; internal set; }
}
public override IActionResult Post([FromBody] TestDto item)
{
if (!IsAdmin)
return BadRequest(ApiErrorCodes.InsufficientPriveleges);
if (!ModelState.IsValid)
return BadRequest(ApiErrorCodes.RequiredFieldsMissing, ModelState.Keys.FirstOrDefault());
}
JS:
var object = JSON.stringify({
createddate: startdate,
retailpriceeur: price,
amountspc: spobicoinprice,
prizesent: false,
expirationdate: expirationdate,
comment: comment,
productgalleryid: productgalleryDto
});
$.ajax({
headers: { "Authorization": "Bearer " + localStorage.getItem('authToken') },
url: "/api/testapi/",
method: "post",
data: object,
contentType: "application/json; charset=utf-8",
success: function (result) {
}
});
Fields in js are also present in the model
Actual: model is not valid.
How me fix that? Please, help
You Shroud send an object not JSON string in ajax request as this example :
var person = new Object();
person.name = "name";
person.surname = "surname";
$.ajax({
url: 'http://localhost:3413/api/person',
type: 'POST',
data: person,
success: function (data, textStatus, xhr) {
console.log(data);
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error in Operation');
}
});
From an ajax call I get some data which I want to pass to another window in a button click. I receive the data successfully but when that data is passed, in controller methods parameter is receiving the value as null.
<script>
$(document).ready(function () {
$('#btnSalesInAmount').click(function () {
var data = {
toDate: $('#todatepicker').val(),
fromDate: $('#fromdatepicker').val(),
customerId: $('#CustomerId').val()
};
$.ajax({
type: 'Get',
url: '/Reports/SalesInAmount' + '?toDate=' + data.toDate + '&fromDate=' + data.fromDate + '&customerId=' + data.customerId,
data: data,
success: function (data) {
window.open("/Reports/SalesInAmountView" + '?salesInAmount=' + data, 'SalesInAmountViewWindow', "features");// the data is not received by controllers method
}
});
});
});
</script>
in controller
public ActionResult SalesInAmountView(SalesInAmount salesInAmount) // parameter value is null
{
return View();
}
the model
public class SalesInAmount
{
public DateTime SalesDt { get; set; }
public int SalesSl { get; set; }
public int CustomerSupplyId { get; set; }
public string CustomerSupplyNm { get; set; }
public double TotalSalesByCustomer { get; set; }
public double TotalDiscount { get; set; }
public double TotalVat { get; set; }
public double TotalSales { get; set; }
public List<SalesInAmount> List { get; set; }
}
Try this ,
Simplify Your Data Set ,
var Param1= $('#ID').val();
var Data = JSON.stringify({ Data1 : Param1, . . });
Ajax
$.ajax({
url: '#Url.Action("Action_Name", "Controller_Name")',
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
data: Data,
cache: false,
success: function (data) {
});
}, error: function (request, status, error) {
}
});
}
Controller
public JsonResult Action_Name(string Data1 , . . )
{
return Json(Some_Json);
}
Note : this Controller Return Json Result , It depends on requirement .
You need to stringify the javascript object before pass as the parameter , JSON.stringify() is the function in javascript
<script>
$(document).ready(function () {
$('#btnSalesInAmount').click(function () {
var data = {
toDate: $('#todatepicker').val(),
fromDate: $('#fromdatepicker').val(),
customerId: $('#CustomerId').val()
};
$.ajax({
type: 'Post',
url: '/Reports/SalesInAmount',
data: JSON.stringify(data),
success: function (data) {
window.open("/Reports/SalesInAmountView" + '?salesInAmount=' + data, 'SalesInAmountViewWindow', "features");// the data is not received by controllers method
}
});
});
});
Make sure you have given same name of variable as you modal class SalesInAmount.
[HttpPost]
public ActionResult SalesInAmountView(SalesInAmount salesInAmount) // parameter value is null
{
return View();
}
I want to use html to get WebApi ReturnValue. (type:Get、datatype:Jsonp)
Now when I direct execution WebApi, it can get ReturnValue "2" (indicate execution Success).
But when via by html + Jquery + ajax , it always show error function information.
How an I resolve this problem, thanks.
------------- code -------------
API Model:
public class LoginModel
{
public int Userno { get; set; }
public List<Second> LoginSecond { get; set; }
}
public class Second
{
public string testinfo01 { get; set; }
public string testinfo02 { get; set; }
public List<Third> Third { get; set; }
}
public class Third
{
public string finValue { get; set; }
}
API Controller:
[HttpGet]
public string Get(string id, string id1) //id=Account,id1=password
{
string conn = ConfigurationManager.ConnectionStrings["testconn"].ConnectionString;
string Dictionary = Login.Login(id, id1).ToString();
return Dictionary;
}
Html:
<div class="form" id="form">
<form class="login-form" method="get">
<input type="text" id="inpAcc" placeholder="Acc"/>
<input type="password" id="inpPwd" placeholder="pwd"/>
<input id="loginbtn" type="button" value="login"></input>
<input id="data" type="label" />
</form>
</div>
jquery + ajax:
<script type="text/javascript" >
$(document).ready(function() {
$(document).on('click', '#loginbtn',function(){
var username = $("input#inpAcc").val();
var password = $("input#inpPwd").val();
alert(username);
var APIurl = "localhost:10733/Api/Login/";
$.ajax({
type: "get",
dataType: 'jsonp',
username:username,
password:password,
url: APIurl +"/"+username+"/"+password,
async: false,
headers: { "cache-control": "no-cache" },
contentType: 'application/json; charset=utf-8',
data :function (data)
{
var returnvalue = data[0].request();
console.log(data.stat);
console.log(data.status);
console.log(data.message);
console.log(data.html);
alert(returnvalue);
},
error: function(request, status, error) {
console.log(request.stat);
console.log(request.status);
console.log(request.message);
console.log(request.html);
alert(request.responseText);
},
success: function(data) {
console.log(data.stat);
console.log(data.status);
console.log(data.message);
console.log(data.html);
alert(data);
}
});
});
});
</script>
Please check your source. Remove the route configuration as below source included route config inline.
[RoutePrefix("api/Login")]
public class LoginController : ApiController
{
[HttpGet]
[Route("Get/{id}/{id1?}")]
public string Get(string id, string id1 = null) //id=Account,id1=password
{
return "Working";
}
}
to call above api your url should be like
http://localhost:11299/api/login/Get/id/id1/
In the above id1 is optional
I have a class with an array property in MVC
public class MyClass
{
public int Contrato_Id { get; set; }
public string Contrato { get; set; }
public int Torre_Id { get; set; }
public string Torre { get; set; }
public SkillsATB[] Skills { get; set; }
}
When I do the POST via jquery ajax my ModelState validation is always false
if (ModelState.IsValid)
{
var _current = _Service.Insert(current);
return Json(new { result = "success", resultValue = "" });
}
debuggin image here here
The property SkillsATB is ok, it has elements, but I think I am missing something for that array.
function ConvertToSkillsObject(id, name) {
var skill = {
Id: Math.round(id),
Nombre: name,
Descripcion: "",
Activo: "1",
Asignada: 1
}
return skill;
}
function GetSkillsAsignados() {
var asignados = [];
$("#sortable2").children().each(function () {
var item = ConvertToSkillsObject($(this).attr("data-id"), $(this).html())
asignados.push(item);
});
return asignados;
}
var MyClass= {
Correo: $('#correo').val(),
CorreoLider: $('#correoLider').val(),
CorreoLiderBSD: $('#correoLiderBSD').val(),
FechaNacio: $('#fechaNacio').val(),
Contrato_Id: $('#contrato_Id').val(),
Torre_Id: $('#torre_Id').val(),
Skills: GetSkillsAsignados()
};
$.ajax({
url: "../../MyController/Save",
type: "POST",
data: JSON.stringify(MyClass),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (e) {
... //more javascript
Remove the property from the model before validating: ModelState.Remove("Skills");
SOLVED
The problem was in a datepicker CSS, something was wrong in the format date. Nothing to do with the prior before
I am currently trying to send an object with a list, but I do not understand why sends the object but the list I receive zero.
Structure:
public class Provider
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Articles> Articles { get; set; }
}
public class Articles
{
public int Id { get; set; }
public string Name { get; set; }
}
Javascript
var articles = [];
articles.push({ Id: 1, Name: "Article Name 1" });
articles.push({ Id: 2, Name: "Article Name 2" });
var provider = {
Id: 1,
Name : "Provider Name",
Articles : articles
};
And i used this call ajax
$.ajax({
contentType: 'application/json; charset=utf-8',
url: "/Provider/Save",
type: 'post',
dataType: 'json',
data: JSON.stringify({ provider: provider}),
cache: false,
success: function (data) {
alert("success");
},
error: function () {
alert("error");
}
});
Controller
[HttpPost]
public ActionResult Save(Provider provider)
{
// Code here
return View();
}