html listbox click event(html helper class) - c#

I am using asp .net mvc 4.0 ,vs2010
I have a listbox and textarea:
<div class="editor-list-field">
#Html.ListBoxFor(model => model.TableColumn, new SelectList(Model.TableColumn), new { #class = "listofcolumn" , name="listofcolumn"})
#Html.ValidationMessageFor(model => model.TableColumn)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Content)
</div>
<div class="editor-multiline-field">
#Html.TextAreaFor(model => model.Content, new { cols=60,#rows=10, #class = "textarea" name = "textarea"})
#Html.ValidationMessageFor(model => model.Content)
</div>
I am wondering, how can i generate an event like listbox_doubleclick(just for example: it could be like anything) and do what i have to.
I have to show the selected items from listbox to textarea for. And i want to do it simply.
I am surfing the net for a solution since yesterday, but could not apply anything to have the job done.
EDIT:
Some jQuery I have tried but no result:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
$(function() {
​$('#listofcolumn')​.dblclick(function() { alert('clicked');
if ($(this).is(':selected')) {
var selectedId = $(this).val();
var selectedText = $(this).text();
alert(selectedText);
$('#textarea').val(selectedText);
}
});
});
</script>

You could use jQuery and dblClick
$('textarea').on('dblclick', function () {
alert('hola');
});

Related

Enable past days on datetime picker

I'm solving a little bug of an application but I have difficulty on a DateTimePicker. In a View of the application I added a DateTimePicker that needs to allow the user to select values in the past. Strangely the object disable the old dates. How can i solve it?
I tried to use DateTimePicker from other pages that actually works as the one i need to implement. But it doesn't work.
That's the code of the page where I'm trying to implement the DateTimePicker.
#{
ViewBag.Title = "CambioTarga";
ViewBag.provenienza = "CambioTarga";
TempData["FromCambioTarga"] = true;
}
<div class="form1">
#Html.Partial("~/Views/Condivise/_Anagrafica.cshtml", (RSM.BusTuristiciBO.SourceDataReference.AnagraficaCliente)ViewBag.anagrafica)
#Html.Partial("~/Views/Condivise/_DatiSocietari.cshtml", (RSM.BusTuristiciBO.SourceDataReference.Dati_Soggetti)ViewBag.dati)
#Html.Partial("~/Views/Condivise/_DettaglioPermesso.cshtml", Model)
#Html.Partial("~/Views/Condivise/_VisuraTargaRidotta.cshtml", (RSM.BusTuristiciBO.SourceDataReference.DatiVisura)ViewBag.datiVisura)
<h4 class="colorH4">Elenco Documenti Allegati Alla Richiesta </h4>
#Html.Partial("~/Views/RichiesteWeb/Dettagli/Trasversali/_ElencoDocumenti.cshtml", (IEnumerable<RSM.BusTuristiciBO.SourceDataReference.Documento>)ViewBag.allegati)
#if (Model.Stato == "PagamentoInValutazione")
{
<div class="row">
<div class="col-sm-4">
#Html.Label("", "Data iniziale", htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.DataInserimento, new { htmlAttributes = new { #class = "form-control datetimepicker", #Value = Model.DataInserimento.ToShortDateString(), required = "required" }, #language = "it", type = "text" })<br />
#Html.ValidationMessageFor(model => model.DataInserimento, "", new { #class = "text-danger" })
</div>
</div>
}
#Html.Partial("~/Views/BTAbbonamenti/_Tariffa.cshtml", (RSM.BusTuristiciBO.SourceDataReference.Tariffa)ViewBag.Tariffa)
<br />
<!-- partial bottoni-->
#Html.Partial("~/Views/RichiesteWeb/Dettagli/Trasversali/_RichiesteButtons.cshtml", Model)
#*#if (Model.Stato != "PagamentoInValutazione")
{
<script>
$('#divPagaRata').hide();
</script>
}
else
{
<script>
$('#btnAccetta').hide();
</script>
}*#
#if (Model.Stato == "InAttesaDiPagamento")
{
<script>
$('#btnAccetta').hide();
</script>
}
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#pnlCambioTarga").hide();
$('#ddlTipoPagamento').val('7');
$("#txtImporto").prop('disabled', true);
$("#ddlTipoPagamento").prop('disabled', true);
$('#btn_VisuraIndietro').hide();
})
</script>```

How to stop page change on Ajax Form Posting in MVC Mobile

I am creating an application on MVC Mobile and having a problem. Here i have a Partial view load on a page run-time by ajax. In which i have a simple form which will submit with ajax request like bellow:
#model Test.Models.TestModel
#using (this.Ajax.BeginForm("Create", "Test", Model, new AjaxOptions { UpdateTargetId = "divResult", LoadingElementId = "loading", LoadingElementDuration = 2000, HttpMethod = "Post" }, new { id = "frmCreate" }))
{
#Html.AntiForgeryToken()
<div class="messageBox">#Html.Raw(TempData["Message"])</div>
<div class="atmForm">
<div class="control-group">
#Html.LabelFor(x => x.Name)
#Html.TextBoxFor(x => x.Name, new { #placeholder = "Name", #class = "inputStyle" }) #Html.ValidationMessageFor(x => x.Name)
</div>
<div class="control-group">
#Html.LabelFor(x => x.Notes)
#Html.TextAreaFor(x => x.Notes, new { #placeholder = "Notes", #class = "inputStyle" }) #Html.ValidationMessageFor(x => x.Notes)
</div>
</div>
<div class="form-actions2 clearfix">
<input type="submit" class="btn btn-block" value="Create" data-ajax="false" id="btnFormSubmit" />
</div>
}
<script type="text/javascript">
$.validator.unobtrusive.parse("#frmCreate");
</script>
The problem is when user submit the form the controller called twice. First time it return the partial view and then again it calls and then jQuery Mobile change the page. I am Using MVC4 with jQuery Mobile 1.1.0
(please note that create.cshtml (desktop ver) works fine but create.Mobile.cshtml (mobility ver) havng this problem)
Do not submit the form, use $("#myForm").serialize() as ajax data.

How do I get the value of my second dropdownlist in MVC4?

I've got these two cascading dropdown lists, they populate just fine. But when I hit submit I always gett NULL as the value of the second. My guess is that I have to do something with the javascript, but my skills in that department are seriously lacking. Please help!
Code removed, whole view added instead
I dont even have an HtmlHelper for the second dropdown, it just looks like this in the view:
Code removed, whole view added instead
Works just fine, I mean, it populates fine depending on what's chosen in the first dropdown. Maybe this is the part that needs alteration? The thing is I'm clueless.
EDIT:
This is the code that reads the information from the form and submits it to the database.
[HttpPost]
public ActionResult Returer(ReturerDB retur)
{
if (ModelState.IsValid)
{
db2.ReturerDB.AddObject(retur);
db2.SaveChanges();
return RedirectToAction("Returer");
}
return View("Returer");
}
EDIT2
The whole view code:
#model Fakturabolag.Models.ReturerDB
#{
ViewBag.Title = "Returer";
}
<script type="text/javascript" src="../../Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#bolag").prop("disabled", true);
$("#Kund").change(function () {
if ($("#Kund").val() != "- Välj bolag -") {
var options = {};
options.url = "/companies/getbolag";
options.type = "POST";
options.data = JSON.stringify({ country: $("#Kund").val() });
options.dataType = "json";
options.contentType = "application/json";
options.success = function (bolag) {
$("#bolag").empty();
for (var i = 0; i < bolag.length; i++) {
$("#bolag").append("<option>" + bolag[i] + "</option>");
}
$("#bolag").prop("disabled", false);
};
options.error = function () { alert("Fel vid bolagshämtning!"); };
$.ajax(options);
}
else {
$("#bolag").empty();
$("#bolag").prop("disabled", true);
}
});
});
</script>
<h2>Returer</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Returer</legend>
<br /><br />
<div class="editor-label">
<b>Kund</b>
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Kund, ViewData["kundLista"] as SelectList)
#Html.ValidationMessageFor(model => model.Kund)
</div>
<div class="editor-label">
<b>Bolag</b>
</div>
<select id="bolag"></select>
<div class="editor-label">
<b>Pris</b>
</div>
<div class="editor-field">
#Html.TextBox("pris", null, new { style = "width: 150px" })
#Html.ValidationMessageFor(model => model.Pris)
</div>
<div class="editor-label">
<b>Datum</b>
</div>
<div class="editor-field">
#Html.TextBox("datum", ViewData["datum"] as String, new { style = "width: 150px" })
#Html.ValidationMessageFor(model => model.Datum)
</div>
<p>
<input type="submit" value="Lägg till" />
</p>
</fieldset>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Currently you are not retrieving the additional value "bolag" in your action. I guess your model does not have property named "bolag". You can either add that or you can add additional parameter to you action like so:
[HttpPost]
public ActionResult Returer(ReturerDB retur, string bolag)
{
if (ModelState.IsValid)
{
db2.ReturerDB.AddObject(retur);
db2.SaveChanges();
return RedirectToAction("Returer");
}
return View("Returer");
}
After that, the selected value from the dropdown should automatically be in the bolag-parameter.
Edit.
You also need to add name-attribute to your select:
<select id="bolag" name="bolag"/>

MVC onfocusout event not firing

Im getting confused about the onfocusout event in my mvc view.
<div class="editor-field" id="supplieridentificationID" >
#Html.EditorFor(m => m.SupplierIdentification)
</div>
<div id="suppliername" class="editor-label" />
And my javascript code:
$('#supplieridentificationID').onfocusout(function () { alert("ajax here!" })
I cant get this to work, actually im trying to send the SupplierIdentification to my controller and get the Json with the SupplierName and put on "suppliername" label.
All using onfocusout function with the ajax.
Any sugestions?
EDIT:
I tried other code, and still not getting nothing:
<div>
<fieldset>
<legend>Novo Documento</legend>
<div class="editor-field" id="ident">
#Html.EditorFor(m => m.SupplierIdentification)
</div>
</fieldset>
</div>
And script:
<script type="text/javascript">
$(document).ready(function() {
$('#ident').focusin(function () { alert("focusin"); });
});
Use focusout instead of onfocusout
$('#SupplierIdentification').focusout(function() { alert("ajax here!" });
try adding an id to control so you can reference it in Jquery.
#Html.EditorFor(m => m.SupplierIdentification, new { #id = "id"})
$(document).ready(function() {
$('#id').blur(function () {
alert("focusin");
});
});
blur function happens when element loses focus

bind and cascade dropdown list mvc 3

My view is
<div id="Countryy">
<div class="editor-label">
#Html.LabelFor(model => model.Country, "Country")
</div>
<div class="editor-field">
#Html.DropDownList("Country", String.Empty)
#Html.ValidationMessageFor(model => model.Country)
</div>
</div>
<div id="Statess">
<div class="editor-label">
#Html.LabelFor(model => model.State, "State")
</div>
<div class="editor-field">
#Html.DropDownList("State", String.Empty)
#Html.ValidationMessageFor(model => model.State)
</div>
</div>
<div id="Cityy">
<div class="editor-label">
#Html.LabelFor(model => model.City, "City")
</div>
<div class="editor-field">
#Html.DropDownList("City", String.Empty)
#Html.ValidationMessageFor(model => model.City)
</div>
</div
MY controller
public ActionResult Edit(int id)
{
Student student = db.Students.Single(s => s.ID == id);
ViewBag.Country = new SelectList(db.Couns, "ID", "CountryName", student.Country);
ViewBag.State = new SelectList(db.States.Where(d => d.CountryID.Equals(student.Country)), "StateID", "StateName", student.State);
ViewBag.City = new SelectList(db.Cities.Where(x => x.StateID.Equals(student.State)), "CityID", "CityName", student.City);
return View(student);
}
Blockquote
My question is how can i cascade the country ,state and city dropdown list.This view is generated when i want to edit the data.the saved data from db is retrived and binded to controls but when user changes the value of country dropdown than state dropdown should also be populated according to it.I have country,state,city 3 different tables in db with the required pk and fk
Here is the Solution for Country and State Cascading Dropdown in MVC using Ajax:-
First dropdown bind by retaining view bag by controller and for second drop down we can use JavaScript/Jquery to fill value based on selected country.
Below code used on cshtml page:
<div class="editor-label">
#Html.LabelFor(m => m.Country)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Country, new SelectList(Model.Country, "Value", "Text"), "Select Contry", new { onchange = "CountryChange()" })
</div>
<div class="editor-label">
#Html.LabelFor(m => m.State)
</div>
<div class="editor-field">
#Html.DropDownList("state","Select State")
</div>
We have used “CountryChange()” javascript function to fetch and fill data in state dropdown based on country change. Below is the JavaScript function implementation.
<script language="JavaScript" type="text/JavaScript">
function CountryChange () {
var url = '#Url.Content("~/Account/GetState")';
var ddlsource = "#Country";
var ddltarget = "#State";
if ($(ddlsource).val() != "") {
$.ajaxSetup({ cache: false });
$.getJSON(url, { Sel_Country: $(ddlsource).val() }, function (data) {
$(ddltarget).empty();
$("#State").append("<option value=''>Select State</option>");
$.each(data, function (index, optionData) {
$("#State").append("<option value='" + optionData.Value + "'>" + optionData.Text + "</option>");
});
});
}
else {
$("#State").empty();
$("#State").append("<option value=''>Select State</option>");
}
}
</script>
Here json url specified “~/Account/GetState” is method “GetState” available in “Account” controller to retrieve data and pass data in json format.
public JsonResult GetState (string Sel_Country)
{
CountryService db = new CountryService ();
JsonResult result = new JsonResult();
var vStateList = db.GetStateList(Convert.ToInt64(Sel_Country));
result.Data = vStateList.ToList();
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return result;
}

Categories