How to show value inside input filed on change of drop down value using zend framework 2 - ajax

I am trying to create an onchange event in zend framework 2. suppose if i change option form dropdown list then the related value will be shown on input field .Here my dropdown works fine .but when i am trying to change dropdown list then there is no value shows on my input field.but the data comes.but not display on broweser.So tell me how it is possible.
Here is My Controller
public function propratingAction()
{
$projectName = $this->propinquity()->projectName();
if($this->getRequest()->isPost())
{
$project =$this->getRequest()->getPost('project');
$projectD = json_decode($project, true);
//print_r($projectD);
$propinquityindex=$this->propinquity()->getproprating($projectD);
$propratingHTML=$this->propratingHTML($propinquityindex);
print_r($propratingHTML);
}
$viewModel = new ViewModel();
$viewModel->setVariables(array('key' => 'value'))
->setTerminal(true);
return $viewModel;
}
public function propratingHTML($propinquityindex){
$html='';
foreach ($propinquityindex as $value) {
# code...
$html .='<input type="text" value="'.$value['critics_rating'].'"/>';
}
print_r($html);
$viewModel = new ViewModel();
$viewModel->setVariables(array("key" => "value"))
->setTerminal(true);
return $viewModel;
}
Here is view part
<div style="display:inline-block; margin-left:55px; margin-top:20px;">
<select style="width:12.5em;" id="project_id" onchange="getsectorindexAjax();"
data-placeholder="Project Name" class="selectError2" data-rel="chosen"
name="project_id" >
<option value="">--select project--</option>
<?php if($this->projectName){
foreach($this->projectName as $val){
echo '<option value="'.$val['project_id'].'">'.$val['Project_name'].'
</option>';
}
} ?>
</select>
</div>
<div class="main" style="display:inline-block; margin-left:10px;margin-top:20px;">
CRc Rating
<input style="width:20em;height:2.7em;" name="critics_rating"
id="critics_rating" type="text" value="">
</div>
ajax call
function getsectorindexAjax()
{
require(["dojo/request", "dojo/query","dijit/registry"], function(request, registry) {
// Locate the JS object.
var project = dojo.byId("project_id").value;
//alert(project);
request.post("http://localhost/admin/propinquity/proprating",{
data : {
project : JSON.stringify(project)
}
}).then(function(text) {
dojo.byId("critics_rating").innerHTML = text;
console.log("return data : " + text);
});
});
}
So suggest me how can i show value inside input field when my dropdown value is change.

You can try something like this :
var dropdown= dijit.byId("project_id"); //get the select element
//on change event
dropdown.on('change', function(evt) {
//get the selected value
var project = dropdown.get("value");
//your ajax request
request.post("http://localhost/admin/propinquity/proprating",{
data : {
project : JSON.stringify(project)
}
}).then(function(text) {
dijit.byId("critics_rating").attr("value", text);
console.log("return data : " + text);
});
});

Related

Laravel 5.5 Controller#destroy DI won't inject model

I have resource controller with following destroy method:
public function destroy(ClinicImage $clinicImage)
{
$clinicImage->delete();
return redirect()->back()->with('success', 'Изображение удалено');
}
Also I have grid with following lines:
<td>
<div class="btn-group btn-group">
<button type="button" data-url="{{route('admin.clinic-image.destroy', [$clinic->id, $image->id])}}" class="btn btn-danger">
<i class="fa fa-remove fa-fw"></i>
</button>
</div>
</td>
And finally I have function to send form on button click:
$('.table').find('.btn.btn-danger').click(function(){
var form = makeForm({_method: 'DELETE'},{action: $(this).data('url')});
form.submit();
});
function makeForm(data, options) {
var form = document.createElement('form');
form.method = 'POST';
var token = document.createElement('input');
token.name = '_token';
token.value = jQuery('meta[name="csrf-token"]').attr('content');
form.appendChild(token);
jQuery.each(data, function(key, value){
var input = document.createElement('input');
input.name = key;
input.value = value;
form.appendChild(input);
});
if(Object.keys(options).length) {
jQuery.each(options, function(option, value){
form[option] = value;
});
}
document.body.appendChild(form);
return form;
}
When i sending form to /admin/clinic/1/clinic-image/1, I get following error:
Type error: Argument 1 passed to App\Http\Controllers\Admin\ClinicImageController::destroy() must be an instance of App\ClinicImage, string given
Controller routes.
So my question is: Why DI do not recognize my route and model id?
Try this one:
public function destroy($clinic, $clinicImage)
{
$clinicImage = ClinicImage::where('id', $clinic)->where('image', $clinicImage); //I'm guessing the name of the columns.
$clinicImage->delete();
return redirect()->back()->with('success', 'Изображение удалено');
}
Actually, you're using wrong argument name in the controller.
Change your signature in a controller.
Instead of $clinicImage change it to $clinic_image
Option 1 : Change in controller
public function destroy(ClinicImage $clinic_image) //$clinicImage to $clinic_image
{
$clinicImage->delete();
return redirect()->back()->with('success', 'Изображение удалено');
}
Option 2 :
Change parameter in route file:
Route::delete('/admin/clinic/{clinic}/clinic-image/{clinicImage})->name('');
Try this in your controller file
public function destroy(ClinicImage $clinicImage)
{
$clinicImage->delete();
return redirect()->back()->with('success', 'Изображение удалено');
}
And in your view file
<td>
<div class="btn-group btn-group">
<button type="button" data-url="{{route('admin.clinic-image.destroy', [$clinic->id])}}" class="btn btn-danger"> (over here you need to pass 1 id at a time which you need to delete)
<i class="fa fa-remove fa-fw"></i>
</button>
</div>
</td>

Jquery Accordion Validation Not working when rendering Partial View through $.ajax call

Hi friends,I am working on MVC 4 Razor and I am stuck in a situation
where Employee Personal Details form is to be filled in
steps(wizard)..for which i used jquery accordion control..for every
step i put an accordion..The html in each accordion section is
rendered from partial view through ajax call on every click of
respective accordion (i.e. <h3></h3> tag)..
On page load first/top accordion is active by default. My problem is
to restrict the user to click on next accordion until he/she fills the
presently active accordion correctly..
Here is my full code:
View:
#model XXX.ViewModels.PersonalDetailsViewModel
#{
ViewBag.Title = "PersonalDetails";
Layout = "~/Views/Shared/Template.cshtml";
}
#using (Html.BeginForm("Lifestyle", "Apply", FormMethod.Post, new { id = "personalDetailForm" }))
{
<div class="centerdiv margin_top20">
<div class="row">
#Html.ValidationSummary(true, "Please Correct the following errors:")
</div>
<div style="width: 1000px;">
<div id="Personalaccordion" class="acordion_div" style="padding: 10px; float: left;">
<h3 class="acordion_div_h3" onclick="javascript:PersonalModule.GetRenderingView('Apply/GetBasicDetailsView','personalDetailForm','BasicDetailsDiv');">
<p>
Basic Details<span id="BasicDetailsDivExp"></span>
</p>
</h3>
<div id="BasicDetailsDiv">
</div>
<h3 class="acordion_div_h3" onclick="javascript:PersonalModule.GetRenderingView('Apply/GetPersonalAddressView','personalDetailForm','PersonalAddressDiv');">
<p>
Address<span id="PersonalAddressDivExp"></span></p>
</h3>
<div id="PersonalAddressDiv">
</div>
</div>
<ul id="conlitue_ul" style="margin-top: 20px;">
<li style="margin-left: 140px;">
<input type="submit" class="compareBtn float_lt" value="Continue Buying >" id="continue" /></li>
</ul>
</div>
</div>
}
#Scripts.Render("~/bundles/PersonalDetails")
<script type="text/javascript">
PersonalModule.GetRenderingView('Apply/GetBasicDetailsView', '', 'BasicDetailsDiv');
</script>
My Controller:
public ActionResult PersonalDetails(int leadId)
{
var personalDetailsViewModel = LeadHelper.GetPersonalDetails(leadId);
return View(personalDetailsViewModel);
}
public ActionResult GetBasicDetailsView(PersonalDetailsViewModel personalDetailsViewModel)
{
if (personalDetailsViewModel.BasicDetails == null)
{
ModelInitializerHelper.InitilaizeBasicDetailsVModel(personalDetailsViewModel);
}
ModelInitializerHelper.InitializeBasicLookup(personalDetailsViewModel);
return PartialView("Personal/BasicDetails", personalDetailsViewModel);
}
public ActionResult GetPersonalAddressView(PersonalDetailsViewModel personalDetailsViewModel)
{
if (personalDetailsViewModel.PersonalAddressDetails == null)
{
ModelInitializerHelper.IntializePersonalAddressVModel(personalDetailsViewModel);
}
ModelInitializerHelper.InitializePersonalAddressLookup(personalDetailsViewModel);
return PartialView("Personal/PersonalAddress", personalDetailsViewModel);
}
My JS :
var PersonalModule = {
GetRenderingView: function (url, formId, containerID) {
var applicationurl = ApplicationRoot + '/' + url;
var objects = $('#BasicDetailsDivExp , #PersonalAddressDivExp' );
viewDivID = containerID;
GetAccordionView(applicationurl, formId, objects, containerID, 'accordion_plus', 'accordion_minus');
}
}
GetAccordionView: function (url, formId, objects, containerID, accordion_plus, accordion_minus) {
var formObjectData = null;
if (formId != undefined) {
formObjectData = $("#" + formId).serialize();
}
var renderView = function (data) {
$('#' + containerID).innerHtml = data;
}
ExpandAccordion(objects, containerID, accordion_plus, accordion_minus);
DoServerRequest(url, formObjectData, renderView);
}
ExpandAccordion: function (objects, spanIconID, accordion_plus, accordion_minus) {
var Objects = objects;
Objects.removeClass(accordion_minus);
Objects.addClass(accordion_plus);
$('#' + spanIconID + 'Exp').removeClass(accordion_plus).addClass(accordion_minus);
if (Browser.ie7) {
Objects.css("margin-top", "-22px");
}
}
DoServerRequest: function (url, data, funSuccess) {
$.ajax({
type: "POST",
url: url,
data: data,
async: false,
dataType: "json",
success: funSuccess,
error: function (errorResponse) {
if (errorResponse.readyState == 4 && errorResponse.status == 200) {
renderCurrentView(errorResponse.responseText)
}
else {
alert(errorResponse.responseText);
}
}
});
}
Please somebody help..I have heard lots of good thing about this forum
and this is my first Question...Thanks in advance..
I have removed my jquery validation attempt as it made the code
garbage thing Now I dont know what to write and where to write
If you are trying to validate data that has been added to form via Ajax after page load then you will need to use the rules method and add rules for these new elements. Jquery Validate has no way of knowing about them otherwise.
Example
Once you have loaded your new content via Ajax you need to find each element and add the necessary rules to them.
$('#yourDiv').find(".newElements").rules("add", {
required: true,
messages: {
required: "Bacon is required"
}
});
If you are using unobtrusive validate you may need to add your new elements to that also. See this SO question for more details.
Validating the Form
To check if the fields are valid, you will need to validate the form on click. This can be done using .validate(). You can then check if the form validated using .valid()
Example
$('#yourForm').validate();
if(!$('#yourForm').valid()) {
alert('Bacon is required');
}

passing drop downlist selected value to Ajax.ActionLink

i have a dropdown list in my view which is populated through model . i want to pass the selected value to
ajax link.
<select name="dd" id="dd">
#foreach (var item in Model)
{
<option value="#item.cid" >
#item.cname</option>
}
</select>
#Ajax.ActionLink("Submit", "Someaction" , new { id = } , new AjaxOptions { UpdateTargetId = "result" })
<div id="result"></div>
how should i route selected value of dropdown ? please help
Selected change action is the client side event, so you cannot handle this event with helpers. But you can use somethink like this:
<select name="dd" id="dd">
#foreach (var item in Model)
{
<option value="#item.cid" >#item.cname</option>
}
</select>
script
$("#dd").change(function() {
var selectedVal = $(this).val();
// in here you have ddl value
// you can pass this parameter with
// ajax and update your result div
$.ajax({
url : 'Home/SomeAction',
data : { selected : selectedValue },
...
success : function(result){
$("#result").html(result);
}
});
});
controller
public ActionResult SomeAction(int selected)
{
// selected is the selected value of DDL...
//return Json/PartialView
}

how to embed telerik dropdown in telerik gridview

I am using telerik controls in my project. How to embed telerik dropdown in telerik grid view with an example project mvc3+razor(cshtml) and controller code is c#?
From Controller just using a TempData or ViewBag to pass data to the View.
List<AdjustmentReasonCodes> salesAuditReasons = new List<AdjustmentReasonCodes>();
salesAuditReasons = salesDal.SalesAuditResonCodes();
TempData["SalesAuditReason"] = salesAuditReasons;
TempData["CStatus"] = salesDal.ReadCustomerListWithRecoveryStatus(objLoginHelper.LogInForUnitCode, Convert.ToByte(ctype), Helper.DateTo(Helper.YearMonthPrevious(2)));
Now just use a list to the view page to hold the TempData
#{
List<AdjustmentReasonCodes> salesAuditReasons = new List<AdjustmentReasonCodes>();
salesAuditReasons = (List<AdjustmentReasonCodes>)TempData["SalesAuditReason"];
}
You can add Combo-box very easy using Template.
<div class="DataGridXScroll">
#{
List<GetCustomerListWithRecoveryStatus> listCustomerStatus = new List<GetCustomerListWithRecoveryStatus>();
listCustomerStatus = (List<GetCustomerListWithRecoveryStatus>)TempData["CStatus"];
if (listCustomerStatus != null)
{
#(Html.Telerik().Grid(listCustomerStatus)
.Name("grvSalesAdjustment")
.DataKeys(keys => keys.Add(k => k.CustCode))
.Columns(column =>
{
column.Bound(a => a.CustCode).Width(100).HtmlAttributes(new { #class = "GridColumnLeftAlign" }).Title("Customer ID");
column.Template(#<input type="text" class="GridTextBoxRightAlign" style="width:62px;" id="#("salesAudit" + #item.CustCode.Replace(" ", "").Replace("-", "").Trim())" value="#(#item.AuditAdjustmentWithoutDPInCurrentMonth.ToString("0"))" />).Title("Audit Adjustment").Width(80);
column.Template(#<select id="#("ddlSalesAuditReason" + #item.CustCode.Replace(" ", "").Replace("-", "").Trim())" class="DropDown">
<option value="0">--Select--</option>
#foreach (AdjustmentReasonCodes adrc in salesAuditReasons)
{
if (item.RefReasonForAuditAdjustment == adrc.ReasonCode)
{
<option value="#(adrc.ReasonCode)" selected="selected">#adrc.ReasonDescription</option>
}
else
{
<option value="#(adrc.ReasonCode)">#adrc.ReasonDescription</option>
}
}
</select>).Title("Audit Reason").Width(135);
}).Selectable()
.Pageable(page => page.PageSize(100))
.Scrollable(scroll => scroll.Height(300))
)
}
}
</div>

Read selected value of drop down in controller

Requirment: I have a drop down and a table on my cshtml page. The drop down displays a list of vendors and the details corresponding to selected vendor are displayed in table. I am submitting the form using jquery when the value of the drop down changes.
Problem: How to cath selected value of drop down in controller?
Code:
#Html.DropDownList("VendorList", new SelectList(Model.vendorList, "vendorId", "vendorName"))
#using (Html.BeginForm("VendorDetails", "VendorLookUp", FormMethod.Post, new { id = "vendorDetailsForm" }))
{
<div class="margin-10-top" >
<table id= "VendorDetail" class="VendorDetail">
........ details of vendor.........
</table>
</div>
}
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$('#VendorList').change(function () {
$('#vendorDetailsForm').submit();
});
});
</script>
the code in my controller is:
[AcceptVerbs("POST")]
public ActionResult SearchResult(FormCollection collection)
{
try
{
string vendorName = collection["searchItem"].ToString();
vendorName = vendorName.Trim();
List<Vendor> vendorList = Queries.compiledVendorQuery(dbContext, vendorName).ToList<Vendor>();
if(vendorList.Count() == 0)
return View("EmptySearch");
Vendor selectedVendor = vendorList[0];
VendorDetails vendorDeatils = Queries.compiledVendorDetailsQuery(dbContext, selectedVendor.vendorId.ToString()).FirstOrDefault();
VendorResult vendorResult = new VendorResult();
vendorResult.vendorList = vendorList;
vendorResult.vendorDetails = vendorDeatils;
return View(vendorResult);
}
catch (Exception e)
{
return View("EmptySearch");
}
}
[AcceptVerbs("POST")]
public ActionResult VendorDetails(FormCollection collection)
{
**here comes the control after postback
require value of the selected item**
Vendor selectedVendor = ??
VendorDetails vendorDeatils = Queries.compiledVendorDetailsQuery(dbContext, selectedVendor.vendorId.ToString()).FirstOrDefault();
VendorResult vendorResult = new VendorResult();
vendorResult.vendorDetails = vendorDeatils;
return View(vendorResult);
}
Since you're not really using the FormCollection, you could just use an int (or whatever the ID is on your model) in your action method:
[HttpPost]
public ActionResult VendorDetails(int vendorId = 0)
{
Vendor selectedVendor = // Load from your data source using vendorId
... // Do the rest of your work
}
In your HTML, move your #Html.DropDownListFor() into your form, rename it to the argument name, then submit the form as normal. Since the display doesn't seem to have any affect on what gets sent to the server, I would pull this out and just leave the #Html.DropDownListFor() in the form:
#using (Html.BeginForm("VendorDetails", "VendorLookUp", FormMethod.Post, new { id = "vendorDetailsForm" }))
{
#Html.DropDownList("vendorId", new SelectList(Model.vendorList, "vendorId", "vendorName"))
}
<div class="margin-10-top" >
<table id= "VendorDetail" class="VendorDetail">
........ details of vendor.........
</table>
</div>
<script type='text/javascript'>
$(document).ready(function () {
$('#vendorId').change(function () {
$('#vendorDetailsForm').submit();
});
});
</script>
Edit
Take a look at this article about MVC's model binding for an idea of how vendorId gets injected from the submitted form. Basically, the binder will match property names with the name attribute (by default) to your model. In this case, our model is just an int.

Resources