How can I get textbox value based on Id in another table? - c#

Why doesn't the textbox Name get value by Id?
So this is view ex_op:
This Id and Name, I get based on tbl_operator. When I entered Id then the Name will show.
This is controller ex_op:
public ActionResult Index()
{
var ex_op = db.ex_op.Include(e => e.tbl_exercises).Include(e => e.tbl_operator);
return View(ex_op.ToList());
}
public ActionResult Create()
{
ex_op exop = new ex_op();
var lasttest = db.ex_op.OrderBy(c => c.idTest).FirstOrDefault();
if (lasttest == null)
{
exop.idTest = "EXOP000";
}
else
{
exop.idTest = "EXOP" + (Convert.ToInt32(lasttest.idTest.Substring(6, lasttest.idTest.Length - 6)) + 1).ToString("D3");
}
ViewBag.idEx = new SelectList(db.tbl_exercises, "idEx","idEx");
ViewBag.idOp = new SelectList(db.tbl_operator, "idOp","idOp");
return View(exop);
}
And this is View ex_op
<div class="form-group">
<label class="control-label col-md-2">Name</label>
<div class="control-label col-md-10">
#Html.EditorFor(model => model.tbl_operator.nama, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.tbl_operator.nama, "", new { #class = "text-danger" })
</div>
</div>
I don't know what I forget in this code, maybe i missing the code
please help me.

To auto fill the Name field once a ID Operator is selected you will need to use events to trigger a call to your Controller and return JSON then fill in the Field.
Client Side:
Checks for a change to the operator id dropdown and send a request to the server.
$('#OperatorId').change(function() {
var str = this.options[this.selectedIndex].value;
$.ajax('#Url.Action("GetOperatorName", "Home")', {
type: 'POST',
dataType: 'json',
data : {'operatorId': str }.
success: function(data, status, jqXHR) {
if ("success" === status) {
document.getElementById('#OperatorName').value = data.OperatorName;
} else {
alert('This Operator ID is not valid. Try again!');
}
}
});
});
Server-side:
Receives the ajax request looks up the operator and return the object
public async Task<JsonResult> GetOperatorName(string operatorId)
{
var item = await Operators.Get(x => x.Id == operatorId);
return Json(item);
}
You will need to change the fields and endpoint etc as needed, but this gives you the idea how to achieve what you need.

Related

Populate one DropDown List from another selected value

I have two drop down list and I've populate them like this :
private List<Client> Client()
{
var allClients= _db.tboClient.Select(x =>
new Tecnico
{
Id = x.Id,
Nome = x.Nome
}).ToList();
return allClients;
}
private List<Pricerice> Price()
{
var allPrice = _db.tboPrice.Select(x =>
new Cliente
{
Id = x.Id,
Nome_azienda = x.Nome_azienda
}).ToList();
return allPrice ;
}
And then some methods that I recall Client() and Price(). I load the View like this :
public IActionResult Create()
{
ViewBag.Price= Pricei();
ViewBag.Clienti = CLienti();
return View();
}
This is the HTML:
<div class="dropdown">
#Html.DropDownListFor(m => m.CLienti, new SelectList(ViewBag.CLienti, "Id", "Nome_azienda"), new { #id = "ddlCLienti", #class = "btn btn-primary dropdown-toggle mr-3" })
</div>
<div class="dropdown">
#Html.DropDownListFor(m => m.Price, new SelectList(ViewBag.Price, "Id", "Nome"), new { #id = "ddlClienti", #class = "btn btn-primary dropdown-toggle mr-3" })
</div>
I want to populate the second(Price) drop down list based on the value selected from the first drop down list.
I want to populate the second(Price) drop down list based on the value selected from the first drop down list.
To achieve above requirement of implement a cascading dropdown, you can try to populate the second dropdown based on the previous selection of the first dropdown on "ddlCLienti" dorpdown change event, like below.
<script>
$(function () {
$("select#ddlCLienti").change(function () {
var CLienti = $(this).val();
$("select#ddlPrice").empty();
$.getJSON(`/your_controller_name_here/GetPriceBySelectedCLienti?CLienti=${CLienti}`, function (data) {
//console.log(data);
$.each(data, function (i, item) {
$("select#ddlPrice").append(`<option value="${item.id}">${item.nome}</option>`);
});
});
})
})
</script>
GetPriceBySelectedCLienti action method
public List<Price> GetPriceBySelectedCLienti(int CLienti)
{
//query data based on selected CLienti
//...

Cascading text box is not working correctly in MVC4?

Hi I have four fields in my view CustomerName, ContactPerson, Email, MobileNo
CustomerName and ContactPerson are Cascading Dropdown, and Email and MobileNo are textboxes.
If I select the CustomerName, related ContactPerson will load automatically in ContactPerson dropdown.
If I select the Contactperson the Contact person related Email and PhoneNo will load automatically in Email and PhoneNo textbox. This works as expected.
Now all are working fine the two cascading drop down are working fine now my issue is if i select the contact person the contact person related Email and phone no is not displaying in that appropriate text boxes.
My Controller Code:
public JsonResult GetCustomers()
{
return Json(db.Customers.ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult GetContactPersobByCustomerId(string customerId)
{
Guid Id = Guid.Parse(customerId);
var customercontacts = (from a in db.CustomerContacts where a.CustomerID == Id select a);
return Json(customercontacts, JsonRequestBehavior.AllowGet);
}
public JsonResult GetPhoneNoByContactPersonID(Guid CustomerContactId)
{
var resultMobileNumber = string.Empty;
var resultEmail = string.Empty;
var ContactID = db.CustomerContacts.Where(i => i.CustomerContactID == CustomerContactId).Select(i => i.ContactID).FirstOrDefault();
if (ContactID != null)
{
var contact = (from p in db.Contacts where p.ContactID == ContactID select p).FirstOrDefault();
if (contact != null)
{
if (string.IsNullOrEmpty(contact.Mobile1) == false)
{
resultMobileNumber = contact.Mobile1;
}
else if (string.IsNullOrEmpty(contact.Mobile2) == false)
{
resultMobileNumber = contact.Mobile2;
}
}
if (contact != null)
{
if (string.IsNullOrEmpty(contact.Email1) == false)
{
resultEmail = contact.Email1;
}
else if (string.IsNullOrEmpty(contact.Email2) == false)
{
resultEmail = contact.Email2;
}
}
}
var details = new { success = true, email = resultEmail, mobileno = resultMobileNumber };
return Json(details, JsonRequestBehavior.AllowGet);
}
View Code:
#Html.Label("Customer Name", new { #class = "control-label" })
#Html.DropDownListFor(model => model.CustomerID, new SelectList(string.Empty, "Value", "Text"), "Please select a Customer", new { #class = "form-control required", type = "text" })
#Html.Label("Contact Person", new { #class = "control-label" })
#Html.DropDownListFor(model => model.CustomerContactID, new SelectList(string.Empty, "Value", "Text"), "Please select a ContactPerson", new { #class = "form-control", type = "text", id = "CustomerContactID" })
#Html.LabelFor(model => model.MobileNo, new { #class = "control-label" })
#Html.TextBoxFor(model => model.MobileNo, new { #class = "form-control", type = "text",disabled = "disabled", #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.MobileNo)
#Html.LabelFor(model => model.Email, new { #class = "control-label" })
#Html.TextBoxFor(model => model.Email, new { #class = "form-control", type = "text" ,disabled = "disabled", #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.Email)
J-query Code
<script src="~/Scripts/jquery-ui-1.11.0.js"></script>
<script>
$(function () {
$.ajax(
'#Url.Action("GetCustomers", "VisitorsForm")',{
type: "GET",
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#CustomerID').append('<option value="' + value.CustomerID + '">' + value.DisplayName + '</option>');
});
}
});
$('#CustomerID').change(function () {
$('#CustomerContactID').empty();
$.ajax(
'#Url.Action("GetContactPersobByCustomerId", "VisitorsForm")',{
type: "POST",
datatype: "Json",
data: { CustomerID: $('#CustomerID').val() },
success: function (data) {
$('#CustomerContactID').append($('<option></option>').val('').text('Please select'));
$.each(data, function (index, value) {
$('#CustomerContactID').append('<option value="' + value.CustomerContactID + '">' + value.ContactReference + '</option>');
});
}
});
});
});
$("#CustomerContactID").change(function () {
alert("hhh");
debugger;
$.ajax(
'#Url.Action("GetPhoneNoByContactPersonID", "VisitorsForm")',{
type: "GET",
dataType: "html",
async: false,
data: { CustomerContactID: $("#CustomerContactID").val()
},
error: function (ex) {
alert('Failed to retrieve Email.' + ex);
},
beforeSend: function () {
},
success: function (data) {
$("#Email").val(data.email);
$("#MobileNo").val(data.mobileno)
alert("Success");
}
});
});
Now all are working fine when i click the contact person it come to the GetPhoneNoByContactPersonID action it calculate the values and return again to the view ans it is also visible in Network too. All are perfect but it not displaying the data in textbox. while i inspect the code it didn't show any error in console. But it shows one warning message which is mentioned below.
Now all are working fine. But i donno why it is not displaying i donno where is the issue is. I tried my level bwst to explain my issue.-please any one help me to clear this issue.
Advance Thanks
There is no id associated with.So assign an id first in TextBoxFor like this.
#Html.TextBoxFor(model => model.MobileNo, new {#id = "MobileNo", #class = "form-control", type = "text",disabled = "disabled", #readonly = "readonly" })
#Html.TextBoxFor(model => model.Email, new {#id = "Email", #class = "form-control", type = "text" ,disabled = "disabled", #readonly = "readonly" })
Now this should work
$("#Email").val(data.email);
$("#MobileNo").val(data.mobileno)

MVC5: Check DropDownList for having Selection (InvalidOperationException)?

I am using BootStrap Switch to show/hide 2 Html.DropDownLists() on one of my MVC5/EF6 Project Views:
<input type="checkbox" value="12345" name="Sponsor-Organization" checked class="userCreate-BSSwitch" />
<div style="margin-bottom: 15px">
<div class="row switchOn">
<div class="editor-label">
#Html.LabelFor(model => model.MemberOrgId, "Organization")
</div>
<div class="editor-field">
#Html.DropDownList("MemberOrgId", ViewData["Organization"] as SelectList, String.Empty, new { #class = "form-control", #id = "MemberOrgId" })
#Html.ValidationMessageFor(model => model.MemberOrgId)
</div>
</div>
<div class="row switchOff">
<dliv class="editor-label">
#Html.LabelFor(model => model.SponsorOrgId, "Sponsor")
</dliv>
<div class="editor-field">
#Html.DropDownList("SponsorOrgId", ViewData["Sponsor"] as SelectList, String.Empty, new { #class = "form-control", #id = "SponsorOrgId" })
#Html.ValidationMessageFor(model => model.SponsorOrgId)
</div>
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script type="text/javascript">
jQuery(document).ready(function () {
setTimeout(function () { $("#alert").alert('close'); }, 5000);
$('.switchOff').addClass('hide');
});
$.fn.bootstrapSwitch.defaults.state = '';
$.fn.bootstrapSwitch.defaults.onText = 'Member';
$.fn.bootstrapSwitch.defaults.offText = 'Sponsor';
$.fn.bootstrapSwitch.defaults.offColor = 'info';
$.fn.bootstrapSwitch.defaults.animate = false;
//$.fn.bootstrapSwitch.defaults.size = 'large';
$(document).ready(function () {
$('input:checkbox[name="Sponsor-Organization"]').bootstrapSwitch();
});
$('input:checkbox[name="Sponsor-Organization"]').on('switchChange.bootstrapSwitch', function (event, state) {
var checked = state;
if (checked) {
$('.switchOn').removeClass('hide');
$('.switchOff').addClass('hide');
$('#SponsorOrgId').val("");
}
else {
$('.switchOff').removeClass('hide');
$('.switchOn').addClass('hide');
$('#MemberOrgId').val("");
}
});
$(document).ready(function () {
$(".btn-danger").click(function () {
var cancel = confirm("Are you sure? Entered data will be lost.")
if (cancel != true) {
event.preventDefault(); // cancel the event
}
});
});
//$('input:checkbox[name="Sponsor-Organization"]').on('switchChange.bootstrapSwitch', function(event, state) {
</script>
Controller Create() Method:
// POST: Admin/UserManagement/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,property1, property2, etc...")] ApplicationUser applicationUser)
{
if ((applicationUser.MemberOrgId == null) && (applicationUser.SponsorOrgId == null))
{
ModelState.AddModelError("", "Must select either an Organization or Sponsor from the dropdown lists.");
return View(applicationUser);
}
if (ModelState.IsValid)
{
ViewBag.headerTitle = "Create User";
applicationUser.UserName = applicationUser.Email;
IdentityResult result = await UserManager.CreateAsync(applicationUser, "r#nd0mP#$S");
if (result.Succeeded)
{
await db.SaveChangesAsync();
return RedirectToAction("Index", "UserManagement");
}
else
{
ModelState.AddModelError("", "Failed to Create User.");
var errors = string.Join(",", result.Errors);
ModelState.AddModelError("", errors);
}
}
ModelState.AddModelError("", "Failed to Create User.");
var errors1 = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToString();
ModelState.AddModelError("", errors1);
ViewData["Organization"] = new SelectList(db.MemberOrganizations, "Id", "Name", applicationUser.MemberOrgId);
ViewData["Sponsor"] = new SelectList(db.SponsorOrganizations, "Id", "Name", applicationUser.SponsorOrgId);
if (applicationUser.MemberOrgId != null)
{
ViewBag.SwitchState = true;
}
else
{
ViewBag.SwitchState = false;
}
ViewBag.OrganizationId = new SelectList(db.MemberOrganizations, "Id", "State", applicationUser.MemberOrgId);
// If we got this far, something failed, redisplay form
return View(applicationUser);
}
This enables me to ensure that ONLY 1 of the DropDownList's have a selection made as I clear the current selection when the current DropDownList is hidden via my JavaScript. What I need now is a way to make sure a selection has been made in the currently displayed list before saving the new Identity User to the database.
Now, my Controller correctly identifies when no selection has been made in either list:
if ((applicationUser.MemberOrgId == null) && (applicationUser.SponsorOrgId == null))
{
ModelState.AddModelError("", "Must select either an Organization or Sponsor from the dropdown lists.");
return View(applicationUser);
}
However, when the View is returned, instead of Model State error I am immediately receiving the below at code line #Html.DropDownList("MemberOrgId", ViewData["Organization"] as SelectList, String.Empty, new { #class = "form-control", #id = "MemberOrgId" }):
InvalidOperationException was unhandled by user code.
An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code
Additional information: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'MemberOrgId'.
Anyone have thoughts on how to better handle this?

How to change the value in Html.TextBox for using Jquery and Json?

In the create view what i am trying to do is when you choose a name from the dropdown list to fill the Login html.TextBoxFor automatically with his details.
Currently the Login textbox remains empty when i choose a person from dropdown list.
So i ve got my json object and tested as well my sql which is fine so i suppose the issue must be somewhere in jquery.
I would be glad if you could help me find the error.
View :
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>User</legend>
<div class="editor-label">#Html.LabelFor(model => model.UserLogin)</div>
<div class="editor-field">#Html.TextBoxFor(model => model.UserLogin, new {id ="LoginId" })
#Html.ValidationMessageFor(model => model.UserLogin)</div>
<div class="editor-label">#Html.LabelFor(model => model.UserFullName)</div>
<div class="editor-field">#Html.DropDownList("UserFullName", ViewBag.UserFullName as SelectList, "Select a User", new { id = "UserID" })
#Html.ValidationMessageFor(model => model.UserFullName)</div>
<p>
<input type="submit"
value="Create" />
</p>
</fieldset> }
<div>#Html.ActionLink("Back to List", "Index")</div>
<script type="text/javascript">
$('#UserID').on('change', function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetUserForm")',
data: { FullName: $('#UserID').val() },
success: function (results){
var login = $('#LoginId');
login.empty();
$.each(results, function ()
{
login.val(this.ID).text(this.Value);
});
}});
});
</script>
Controller:
public ActionResult Create()
{
var names = StaffDB.StaffData.AsEnumerable().Select(s => new
{
ID = s.ID,
FullName = string.Format("{0} {1}", s.Forename1, s.Surname)
}).ToList();
if(ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.UserFullName = new SelectList(names, "FullName", "FullName", user.UserFullName);
return View(user);
}
[HttpPost]
public JsonResult GetUserForm(string FullName)
{
//pseudo code
var data = from s in StaffDB.StaffData
where s.Forename1 + ' ' + s.Surname == FullName
select new
{
Value = s.Login,
ID = s.ID
};
return Json(data);
}
I think the issue is while returning the json, In MVC by default Jsonresult is "Deny get", so you have add "Allow Get".
[HttpPost]
public JsonResult GetUserForm(string FullName)
{
//pseudo code
var data = from s in StaffDB.StaffData
where s.Forename1 + ' ' + s.Surname == FullName
select new { Value = s.Login, ID = s.ID };
if (data == null)
return Json(null);
return Json(data , JsonRequestBehavior.AllowGet);
}

Getting information from my controller into onclick confirm(alert)

i try to confirm a sale and i need sum information about the product..
my View
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Card</legend>
<div class="editor-label">
#Html.LabelFor(model => model.CardModel.SerialNumber, "Serial No")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CardModel.SerialNumber, new { id = "sn" })
#Html.ValidationMessageFor(model => model.CardModel.SerialNumber)
</div>
<p>
<input type="submit" value="CardSale" id="btnSubmit"
onclick="if (confirm('The owner dealer price is : **#Model.OwnerPrice** . Are you sure?')) { return true; } else { return false; }" />
</p>
</fieldset>
}
i tryed with the ' $.getJSON ' like this:
<script type="text/javascript">
$(document).ready(function()
{
$("#btnSubmit").click(function ()
{
var serial = $("#sn");
var price = "";
var url = "";
url = "#Url.Action("GetOwnerPrice","Card")/"+serial;
$.getJSON(url,function(data)
{
alert(data.Value);
});
});
});
and on the controller
public ActionResult GetOwnerPrice(int sn)
{
var owner = db.Dealers.Single(s => s.DealerID == db.Dealers.Single(o => o.UserName == User.Identity.Name).OwnerDealerID);
var ownerPrice = owner.ProductToSale.Single(pr => pr.ProductID == sn).SalePrice;
return Json(ownerPrice, JsonRequestBehavior.AllowGet);
}
but i dont know how to return it to the onclick confirm msg or into my ViewModel..
any help?
The way in which you have written it, the #Model.OwnerPrice value must be known during page generation, since the template engine only has values that exist in your model when it does the template-data merge.
If you do know this value during page load, then simply use the value in your model exactly as you have, and if the user ever gets to this dialog, they will see the proper value.
If the value of this confirmation dialog is not known during page load, then you have the right idea to retrieve it via an Ajax call. The trick is to update the DOM with the new information when the call finishes. You can do this in three steps. First, change your dialog box:
First:
if (confirm('The owner dealer price is : ' + ownerDealerPrice + '. Are you sure?'))
Second:
Declare a new global variable:
var ownerDealerPrice;
Third:
Get the price:
$.ajax({ url: "/GetOwnerPrice", type: "GET", data: "serial=" + serial })
.success(function (price) {ownerDealerPrice = price; }
});
finnaly i take the two answare =)
my view:
#model oCc.IPToGo.ViewModel.CardSaleViewModel
#{
ViewBag.Title = "Card Sale";
var ownerDealerPrice = 0;
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Card</legend>
<div class="editor-label">
#Html.LabelFor(model => model.CardModel.SerialNumber, "Serial No")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CardModel.SerialNumber)
#Html.ValidationMessageFor(model => model.CardModel.SerialNumber)
</div>
<p>
<input type="submit" value="CardSale" />
</p>
</fieldset>
}
<script type="text/javascript">
$(document).submit(function()
{
var serial = "";
serial = $("#CardModel_SerialNumber").val();
var uurl = "";
uurl = "#Url.Action("GetOwnerPrice","Card")/"+serial;
$.ajaxSetup({ cache: false });
$.ajax({ async: false , url: uurl, dataype : 'json', method : 'GET'})
.success(function (price) {ownerDealerPrice = price;
$.ajaxSetup({ cache: true });
});
return (confirm('The owner dealer price is : ' + ownerDealerPrice + '. Are you sure?'))
});
the controller code
public ActionResult GetOwnerPrice(string ID)
{
var currentDealer = db.Dealers.Single(o => o.UserName == User.Identity.Name);
var owner = db.Dealers.Single(s => s.DealerID ==currentDealer.OwnerDealerID);
var card = db.Cards.Single(s => s.SerialNumber == ID);
var ownerPrice = owner.ProductToSale.Single(pr => pr.ProductID == card.ProductID).SalePrice;
return Json(ownerPrice, JsonRequestBehavior.AllowGet);
}
Did you try $.ajax with async = false?
It will return control right into your click handler. Something like:
var tmp = 0;
$.ajax({
async = false,
url = ...,
dataype = 'json',
method = 'POST'})
.complete(function(data) {
tmp = data
});
if(confirm("my message here: " + tmp)) {... }

Categories