The Following is the View :
<div class="editor-label">
Select Currency :
</div>
<div class="editor-field">
#Html.DropDownList("CurrencyId", new SelectList(ViewBag.CurrencyId, "Value", "Text"))
</div><div class="editor-label">
Select GameType :
</div>
<div class="editor-field">
#Html.DropDownList("GameTypeId", new SelectList(ViewBag.GameTypeId, "Value", "Text"), new { style = "width:100px" })
#Html.ValidationMessageFor(model => model.GameTypeId)
</div>
<div class="editor-label">
Select Category :
</div>
<div class="editor-field">
#Html.DropDownList("CategoryByGameType", Enumerable.Empty<SelectListItem>(), "Select Category")
#Html.ValidationMessageFor(model => model.CategoryId)
</div>
The following is Controller:-
public ActionResult Create()
{
List<Currency> objCurrency = new List<Currency>();
objCurrency = db.Currencies.ToList();
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem()
{
Value = "0",
Text = "Select Currency"
});
foreach (Currency item_Currency in objCurrency)
{
listItems.Add(new SelectListItem()
{
Value = item_Currency.CurrencyId.ToString(),
Text = item_Currency.CurrencyName
});
}
ViewBag.CurrencyId = new SelectList(listItems, "Value", "Text");
List<GameType> objgametype = objGameByGameType.GetDistinctGameTypeID();
List<SelectListItem> listItems_1 = new List<SelectListItem>();
listItems_1.Add(new SelectListItem()
{
Value = "0",
Text = "Select Game Type"
});
foreach (GameType item_GameType in objgametype)
{
listItems_1.Add(new SelectListItem()
{
Value = item_GameType.GameTypeId.ToString(),
Text = item_GameType.GameTypeName
});
}
ViewBag.GameTypeId = new SelectList(listItems_1, "Value", "Text");
return View();
}
The following is my Jquery for i am using Casceding Dropdown
$(function () {
$("#GameTypeId").change(function () {
var theatres = "";
var gametype = "";
var mytestvar = "";
var gametypeid = $(this).val();
mytestvar += "<option value= -1 >Select Category</option>";
$.getJSON("#Url.Action("GetCategoryByGameType", "GameCombination")?gametypeid=" + gametypeid, function (data) {
$.each(data, function (index, gametype) {
// alert("<option value='" + gametype.Value + "'>" + gametype.Text + "</option>");
mytestvar += "<option value='" + gametype.Value + "'>" + gametype.Text + "</option>";
});
//alert(mytestvar);
$("#CategoryByGameType").html(mytestvar);
$("#GamebyCategory").html("<option value=0>Select Game</option>");
$("#LimitVariantByGameByGameType").html("<option value=0>Select Limit Variant</option>");
$("#StakeCategory").html("<option value=0>Select Stake Category</option>");
$("#StakeBuyInByStakeCategory").html("<option value=0>Select Stake Buy In By Stake Category</option>");
});
});
});
While submit data i am not able to get back the dropdown value if Error come on creation
Echo of what Andras said, you can't use razor syntax in a .js file if that's happening.
Also you should get familiar with your debugging tools, what browser are you using? Most have a nice set of developer tools (some have them built in) where you can inspect the page and the request sent out when you submit the form.
You could interactively use jquery in the console of your browser to look around also.
You don't show your post create method, perhaps it is related to that code?
This should give you an idea of what you can do.
I would suggest that you move the ajax into its own function and the $.each into its own function and call the $.each function out of the ajax function and the ajax function out of the main function.
$(function () {
$("#GameTypeId").change(function () {
var theatres = "";
var gametype = "";
var mytestvar = "";
var gametypeid = $(this).val();
mytestvar += "<option value= -1 >Select Category</option>";
$.ajax({
url: '/GameCombination/GetCategoryByGameType',
type: 'GET',
data: { "gametypeid": gametypeid},
dataType: 'json',
success: function (data) {
$.each(data, function (index, gametype) {
// alert("<option value='" + gametype.Value + "'>" + gametype.Text + "</option>");
mytestvar += "<option value='" + gametype.Value + "'>" + gametype.Text + "</option>";
});
//alert(mytestvar);
$("#CategoryByGameType").html(mytestvar);
$("#GamebyCategory").html("<option value=0>Select Game</option>");
$("#LimitVariantByGameByGameType").html("<option value=0>Select Limit Variant</option>");
$("#StakeCategory").html("<option value=0>Select Stake Category</option>");
$("#StakeBuyInByStakeCategory").html("<option value=0>Select Stake Buy In By Stake Category</option>");
},
error: function (error) {
alert(error.toString());
}
});
});
});
You have to create a object for dropdownlist in View.cs and then assign the value. After that when u try to get the dropdown values u have to use the ViewBag title object name and then the dropdownlist value.
Below code specifies for the radiobutton. You can alter it for dropdown
#model MVC_Compiler.Models.UserProgram
#{
ViewBag.Title = "UserProgram";
}
<table style="background-color: #FBF9EF;">
<colgroup>
<col style="width: 20%;">
<col style="width: 80%;">
</colgroup>
<tr>
<td style="vertical-align: text-top">
#Html.RadioButtonFor(up => up.Language, "C")C<br />
#Html.RadioButtonFor(up => up.Language, "C++")C++<br />
#Html.RadioButtonFor(up => up.Language, "C#")C#<br />
#Html.RadioButtonFor(up => up.Language, "VB")VB<br />
#Html.RadioButtonFor(up => up.Language, "Java")Java<br />
#Html.RadioButtonFor(up => up.Language, "Perl")Perl<br />
#Html.HiddenFor(up => up.Language, new { #id = "Select_Language" })
#Html.HiddenFor(up => up.UserName, new { #id = "UserName" })
</td>
Then in Models you can get the radio button value by following way:
userProgram.Language
where userProgram is ViewBag Title.
Related
I am using jQuery to set the second dropdown list items on selection of the first dropdown. At the time of edit action I want to set fetched data to the second dropdown list. I want to set ViewBag.UserLinkedList to the second dropdown list.
View:
<div class="form-row">
<div class="col-lg-7">
#Html.Label("User Type") #Html.DropDownListFor(m => m.LoginUserTypeID(SelectList)ViewBag.LoginUserTypeList, "--- Select User Type ---", new { #class = "form-control" })
</div>
</div>
<div class="form-row">
<div class="col-lg-7">
#Html.Label("Parent User") #Html.DropDownListFor(m => m.UserLinkedID, new SelectList(""), "--- Select ---", new { #class = "form-control" })
</div>
<script>
$(document).ready(function() {
$("#LoginUserTypeID").change(function() {
$.get("/User/GetParentUserList", {
UserTypeID: $("#LoginUserTypeID").val()
}, function(data) {
$("#UserLinkedID").empty();
$.each(data, function(index, row) {
$("#UserLinkedID").append("<option value='" + row.Id + "'>" + row.Name + "</option>")
});
});
})
});
</script>
Controller:
public JsonResult GetParentUserList(int UserTypeID)
{
List<V_Dealer_DealerEmployee> LinkedIDList = new List<V_Dealer_DealerEmployee>();
if (UserTypeID == 1 || UserTypeID == 2)
{
var d = from s in db.VDNSEmployeeMaster
select new
{
Id = s.EmpId,
Name = s.FirstName + " " + s.MiddleName + " " + s.LastName
};
d.ToList();
return Json(d.ToList(), JsonRequestBehavior.AllowGet);
}
else
{
var unionAll = (from word in db.VDNSDealer select new
{
Id = word.m_code,
Name = word.institute_name
}).Concat(from word in db.DealerEngineerMaster select new {
Id = word.EnggId,
Name = word.EngineerName
});
return Json(unionAll.ToList(), JsonRequestBehavior.AllowGet);
}
}
Edit Action
public ActionResult Edit(int id)
{
var user = db.Users.SingleOrDefault(c => c.Id == id);
if (user == null)
return HttpNotFound();
List<LoginUserType> LoginUserTypeList = db.LoginUserType.ToList();
ViewBag.LoginUserTypeList = new SelectList(LoginUserTypeList, "UserTypeId", "UserTypeName");
List<V_Dealer_DealerEmployee> UserLinkedList = db.VDealerDealerEmployee.ToList();
ViewBag.UserLinkedList = new SelectList(UserLinkedList, "Id", "Name");
return View("New", user);
}
After returning view from edit action, you need to call your change function of LoginUserTypeID. Here is the required js for you
function UpdateUserLinkedIdDropdown(){
var userTypeId = $("#LoginUserTypeID").val();
//This check is for no options selected in LoginUserTypeID Dropdown
if(userTypeId === null || userTypeId === "" || userTypeId === undefined)
userTypeId = 0;
$.get("/User/GetParentUserList", {
UserTypeID: userTypeId
}, function(data) {
$("#UserLinkedID").empty();
$.each(data, function(index, row) {
$("#UserLinkedID").append("<option value='" + row.Id + "'>" + row.Name + "</option>")
});
});
}
$("#LoginUserTypeID").change(function() {
UpdateUserLinkedIdDropdown();
});
// Call it initially when view loaded
// You can do it in this way
UpdateUserLinkedIdDropdown();
// OR This way
$("#LoginUserTypeID").trigger('change');
Give it a try! I think this will work. If not comment plz
The issue I am facing is similar to this old post cascading dropdown for dynamically added row. I am using the "BeginCollectionItemCore" NuGet package to setup a set of partial views, so I have unique Id's for my controls. The problem is, I can only get the first Partial View to respond to the dropdownlist changes. The subsequent dropdownlists won't cascade. I have tried with the scripts in the partial and in the main view but both have the same end result, only the first partial will cascade. Here is my code...
Main View HTML:
#model IEnumerable<RCRTCWA.DATA.DAL.tbl_RCRTimeCards>
#{
ViewBag.Title = "Index";
}
<h2>Time Card</h2>
#using (Html.BeginForm())
{
<div id="TimeCardLines">
#foreach (var item in Model)
{
Html.RenderPartial("_TimeCardRow", item);
}
</div>
}
#Html.ActionLink("Add more time...", "_TimeCardRow", new { ViewContext.FormContext.FormId }, new { id = "addTime"})
Main View Script:
<script>
$(document).ready(function () {
debugger;
$("#addTime").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#TimeCardLines").append(html); }
});
return false;
});
//var index = "";
$(".timecardrow").focusin(function () {
var ti = $(this).find("[name='timecardrows.index']");
var index = ti.val();
$("#timecardrows_" + index + "__HRS_EndTime").timepicker({
defaultTime: 'now',
minTime: '6:00am',
maxTime: '7:00pm'
});
$("#timecardrows_" + index + "__HRS_StartTime").timepicker({
defaultTime: 'now',
minTime: '6:00am',
maxTime: '7:00pm'
});
//$("#.Line_TimeCard").ajaxSuccess(function () {
// $.getJSON("/TimeCard/AddTimeCardRow/", $("#.Success").html(data).show());
//});
$("#timecardrows_" + index + "__WOTicketNo").change(function () {
var tktid = $(this).val();
$("#timecardrows_" + index + "__WOTicketRepLineNo").empty();
$.ajax({
url: "/TimeCard/GetRepairLines/",
data: { ticket: tktid },
cache: false,
type: "POST",
success: function (data) {
$.each(data, function (i, data) {
$("#timecardrows_" + index + "__WOTicketRepLineNo").append('<option value="' + data.Value + '">' + data.Text + '</option>');
});
},
error: function (response) {
alert("Error : " + response);
}
});
GetCarNumber(tktid);
});
$("#timecardrows_" + index + "__WOTicketRepLineNo").change(function () {
var line = $("#timecardrows_" + index + "__WOTicketRepLineNo").val();
$("#timecardrows_" + index + "__WOTicketLaborLineNo").empty();
$.ajax({
url: "/TimeCard/GetLineDetails/",
data: { lineid: line },
cache: false,
type: "POST",
success: function (data) {
$.each(data, function (i, data) {
$("#timecardrows_" + index + "__WOTicketLaborLineNo").append('<option value="' + data.Value + '">' + data.Text + '</option>');
});
},
error: function (response) {
alert("error : " + response);
}
});
return false;
}).change();
function GetCarNumber(ticket) {
$.ajax({
url: "/TimeCard/GetCarNumber/",
data: { ticket: ticket },
cache: false,
type: "POST",
success: function (data) {
$("#timecardrows_" + index + "carNo").html(data).show();
},
error: function (response) {
alert("Error : " + response);
}
});
}
});
});
</script>
Partial View HTML:
#using HtmlHelpers.BeginCollectionItem
#model RCRTCWA.DATA.DAL.tbl_RCRTimeCards
<div class="timecardrow">
#using (Html.BeginCollectionItem("timecardrows"))
{
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<table>
<tr>
<th class="col-sm-1">
Ticket Number
</th>
<th class="col-sm-1">
Car Number
</th>
<th class="col-sm-1">
Repair Line / Description
</th>
<th class="col-sm-1">
Labor Line / Description
</th>
<th class="col-sm-1">
Start Time
</th>
<th class="col-sm-1">
End Time
</th>
<th class="col-sm-1">
Line Complete?
</th>
</tr>
<tr>
<td class="form-group">
<div class="col-sm-1 tickets">
#Html.DropDownListFor(model => model.WOTicketNo, (SelectList)ViewData["TicketsList"], "Select one...", new { #class = "ticketddl" } )
#Html.ValidationMessageFor(model => model.WOTicketNo, "", new { #class = "text-danger" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 cars">
<div id="carNo"></div>
#Html.HiddenFor(model => model.CarNo)
#Html.ValidationMessageFor(model => model.CarNo, "", new { #class = "text-danger" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 replines">
#Html.DropDownListFor(model => model.WOTicketRepLineNo, new SelectList(string.Empty, "Value", "Text"), "Select one...", new { #class = "repairddl" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 laborlines">
#Html.DropDownListFor(model => model.WOTicketLaborLineNo, new SelectList(string.Empty, "Value", "Text"), "Select one...", new { #class = "lablineddl" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 starttime">
#Html.EditorFor(model => model.HRS_StartTime, new { #class = "start" })
#Html.ValidationMessageFor(model => model.HRS_StartTime, "", new { #class = "text-danger" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 endtime">
#Html.EditorFor(model => model.HRS_EndTime, new { #class = "end" })
#Html.ValidationMessageFor(model => model.HRS_EndTime, "", new { #class = "text-danger" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 completed">
#Html.EditorFor(model => model.Completed)
#Html.ValidationMessageFor(model => model.Completed, "", new { #class = "text-danger" })
</div>
</td>
#*<td class="form-group">
<div class="col-sm-1">
<input type="submit" value="Submit Line" class="btn btn-default" />
</div>
<div id="success" class="alert-danger">
</div>
</td>*#
</tr>
</table>
</div>
}
</div>
Currently I have the script in the Main View, and have attempted to get the index part of the partial view's controls when the user interacts with the partial view. I need a better way to handle this, and need to get the cascading dropdownlist's working properly.
I would prefer to have the script in the Main View (if possible) to keep things simpler.
You do not need to bind the change event handler on dropdown using concatenated id strings, which is prone to errors (typos etc) and not easily readable/maintainable. For your cascading dropdown scenario, all you care about is updating the second select element in the same row. jQuery has some handy methods like closest and find which will make our life easier.
For making it easier for future readers, I am going to assume that your first SELECT element is to render a list of countries and has a css class "countrySelect" and second one is for the states of selected country and has the css class "statesSelect" and both are in the same table row (<tr>).
When you bind the change event, make sure you use jQuery on to do so. This will enable the binding for current and future elements in the DOM .
$("#TimeCardLines").on("change","SELECT.countrySelect",function (e) {
var _this = $(this);
var v = _this.val();
// to do :Change below url variable value as needed for your code
var urlToGetSecondDropDownData = "/Home/GetStates?countryId"+v;
$.getJSON(urlToGetSecondDropDownData,
function (res) {
var items = "";
$.each(res,
function(index, item) {
items += "<option value='" + item.Value + "'>"
+ item.Text + "</option>";
});
_this.closest("tr") // Get the same table row
.find("SELECT.statesSelect") // Find the second dropdown
.html(items); // update the content of it
});
});
Assuming you have a GetStates action method which accepts a countryId param and return the corresponding states as a list of SelectListItem ( the data needed to build the second dropdown). Something like below,
public ActionResult GetStates(int countryId)
{
var states =db.States.Where(f => f.CountryId == countryId)
.Select(f => new SelectListItem() { Value = f.Id.ToString(),
Text = f.Name})
.ToList();
return Json(states, JsonRequestBehavior.AllowGet);
}
//first dropdowlist change event
$("#countryId").change(function () {
var id = this.value;
if (id == "") {
id = "0";
}
$.get('/Home/GetStates/' + id,
function (data) {
$('#stateId').find('option').remove()
$(data).each(
function (index, item) {
$('#stateId').append('<option value="' + item.Value + '">' + item.Text + '</option>')
});
}
);
});
public ActionResult GetStates(int id)
{
List<SelectListItem> StatesList= new List<SelectListItem>();
StatesList.Add(new SelectListItem { Text = "---Select State---", Value = "0" });
var getStateCollection= (from f in _ent.States
where f.CountryId == id && f.DeletedDate == null
select new { f.Id, f.Name}).ToList();
foreach (var item in getStateCollection)
{
StatesList.Add(new SelectListItem { Text = item.Name.ToString(), Value = item.Id.ToString() });
}
return Json(StatesList, JsonRequestBehavior.AllowGet);
}
I have a working cascading dropdown list, whereby, once I select one value, it populates the second dropdown by use of JSON. I don't know how to pass this second dropdownlist index (and also whenever it is changed) to my controller to display corresponding data from my model.
My json dropdownlist is as follows
$(function () {
$('#VoyageDivID').hide();
$('#tabsDiv').hide();
$('#Vessel_ID').change(function () {
var URL = $('#VesselVoyageFormID').data('voyagelistaction')+'/' + $('#Vessel_ID').val();
$.getJSON(URL, function (data) {
var items = "";
$.each(data, function (i, voyage) {
items += "<option value='" + voyage.Value + "'>" + voyage.Text + "</option>";
});
$('#Voyage_ID').html(items);
$('#VoyageDivID').show();
$('#tabsDiv').show();
});
});
$('#Voyage_ID').change(function () {
$('#tabsDiv').show();
//need to show the related data here whenever the dropdownlist is changed
});
});
VIEW
<div id="tabsDiv">
<div class="editor-label">
XYZ
</div>
<div class="editor-field">
#Html.EditorFor(model => model.XYZ)
</div>
</div>
CONTROLLER
public ActionResult VoyageList(int ID)
{
// int voyageID = ID;
var voyages = from s in db.EXAMPLE.OrderByDescending(i => i.Voyage_ID).ToList()
where s.Vessel_ID == ID
select s;
if (HttpContext.Request.IsAjaxRequest())//only if it comes from list
return Json(new SelectList(
voyages.ToArray(),
"Voyage_ID",
"Voyage_ID")
, JsonRequestBehavior.AllowGet);
return RedirectToAction("Index");
}
I have to do one dropdownlist and one listbox. When I select a value in dropdownlist, the listbox has to change. I'm trying to do this with Jquery, because I'm using MVC. But when I select the ID in the first dropdownlist, nothing happens. My code:
View (Jquery):
<script type="text/javascript">
$(document).ready(function () {
$('#IDCONCESSAO').change(function () {
$.ajax({
url: '/Localidades/LocalidadesMunicipio',
type: 'POST',
data: { ConcessaoId: $(this).val() },
datatype: 'json',
success: function (data) {
var options = '';
$.each(data, function () {
options += '<option value="' + this.IdLocalidade + '">' + this.NomeLocalidades + '</option>';
});
$('#IDLOCALIDADE').prop('disabled', false).html(options);
}
});
});
});
</script>
Dropdownlist and listbox part:
<%: Html.DropDownListFor(model => model.SINCO_CONCESSAO, new SelectList(ViewBag.IDCONCESSAO, "Id", "Nome"), new { #class = "select", style = "width: 250px;" }) %>
</div>
<div class="editor-label" style="font-weight: bold">
Localidades:
</div>
<div class="editor-field" id="Localidades">
<%: Html.ListBoxFor(m => m.SelectedItemIds, Model.ItemChoices, new { id = "IDLOCALIDADE", size = "10" })%>
</div>
The action that do the cascade:
[HttpPost]
public ActionResult LocalidadesMunicipio(int ConcessaoID)
{
var Localidades = (from s in db.LOCALIDADES_VIEW
join c in db.SINCO_CONCESSAO.ToList() on s.ID_MUNICIPIO equals c.IDMUNICIPIO
where c.IDCONCESSAO == ConcessaoID
select new
{
idLocalidade = s.ID_LOCALIDADE,
NomeLocalidades = s.NOME_LOCALIDADE
}).ToArray();
return Json(Localidades);
}
Controller:
[Authorize(Roles = "ADMINISTRADOR")]
public ActionResult Create(SINCO_LOCALIDADE_CONCESSAO model)
{
//Here I populate my dropdownlist
ViewBag.IDCONCESSAO = from p in db.SINCO_CONCESSAO.ToList()
join c in db.MUNICIPIOS_VIEW.ToList() on p.IDMUNICIPIO equals c.ID_MUNICIPIO
join d in db.SINCO_TIPO_CONCESSAO.ToList() on p.IDTIPOCONCESSAO equals d.IDTIPOCONCESSAO
select new
{
Id = p.IDCONCESSAO,
Nome = p.IDCONCESSAO + " - " + c.NOME_MUNICIPIO + " - " + d.DSTIPOCONCESSAO
};
//Here I populate my listbox
PopulateItemLocalidades(model);
return View(model);
}
I can't see what is wrong T_T
What I am missing?
The first drop down most likely has an ID of SINCO_CONCESSAO, by the name of the property it was created for. And you are referring to something different in your script.
To fix this, either specify a different ID in jQuery:
$('#SINCO_CONCESSAO').ajax ...
or set an ID for a dropdown in View:
<%: Html.DropDownListFor(model => model.SINCO_CONCESSAO, ...
, new { id = "IDCONCESSAO" ... }) %>
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)) {... }