How to pass list items from controller to view - view

I have a partialview and an action method in controller. In the action method I have different lists which I am binding to view, for my first div I am getting only single value but in my second list I may get multiple values which I need to pass them to view. When I am trying to passing them to view I am getting error. How can I pass list data from controller to view in mvc?
I was trying in this way by using for each loop but its not working
#foreach(var item in Model)
{
#if ((item.Name1 != null))
{
<p> #item .Name1 </p>
}
else
{
<p> Not Available</p>
}
}
Controller
public ActionResult ViewInfo(long Id = 0)
{
UviewAhsPhMemberInfoProxyStub model = new UviewAhsPhMemberInfoProxyStub();
try
{
esParameters parameters = new esParameters();
parameters.Add("Id", Id);
List<UviewBasicdataProxyStub> lstbasicdata = _resource.Activity.GetPhMemberInfo(parameters, timeDictionary).Result;
List<UviewAdditionaldataProxyStub> lstadditionaldata = _resource.Activity.GetPhContactInfo(param).Result;
if (lstbasicdata.Count > 0)
{
var basicdata= lstbasicdata[0];
model.Name1 = basicdata.Name1.SetStringOrNotAvailable("Not Available");
model.Name2 = basicdata.Name2.SetStringOrNotAvailable("Not Available");
model.Name3 = basicdata.Name3.SetStringOrNotAvailable("Not Available");
model.Name4 = basicdata.Name4.SetStringOrNotAvailable("Not Available");
}
if (lstadditionaldata.Count > 0)
{
var additionaldata = lstadditionaldata[0];
model.Number1 = ConactInfo.Number1.SetStringOrNotAvailable("Not Available");
model.Number2 = ConactInfo.Number2.SetStringOrNotAvailable("Not Available");
model.Number3 = ConactInfo.Number3;
model.Number4 = ConactInfo.Number4.SetStringOrNotAvailable("Not Available"); //county
model.Number5 = ConactInfo.Number5.SetStringOrNotAvailable("Not Available");
}
}
catch (Exception ex)
{
ex.Message.ToString();
}
return PartialView(model);
}
View-
//first div
<div class="row" style="max-height:450px;overflow-y:auto;width:100%">
<div class="column">
<p style="font-weight: 700;"> Name1 </p>
#if ((Model.Name1 != null))
{
<p> #Html.DisplayFor(model => model.Name1) </p>
}
else
{
<p> Not Available</p>
}
</div>
<div class="column">
<p style="font-weight: 700;"> Name2 </p>
#if ((Model.Name2 != null))
{
<p> #Html.DisplayFor(model => model.Name2) </p>
}
else
{
<p> Not Available</p>
}
</div>
<div class="column">
<p style="font-weight: 700;"> Name3 </p>
#if ((Model.Name3 != null))
{
<p> #Html.DisplayFor(model => model.Name3) </p>
}
else
{
<p> Not Available</p>
}
</div>
<div class="column">
<p style="font-weight: 700;"> Name4 </p>
#if ((Model.Name4 != null))
{
<p> #Html.DisplayFor(model => model.Name4) </p>
}
else
{
<p> Not Available</p>
}
</div>
</div>
//second div
<div class="row" style="max-height:450px;overflow-y:auto;width:100%">
<div class="column">
<p style="font-weight: 700;"> Number1 </p>
#if ((Model.Number1 != null))
{
<p> #Html.DisplayFor(model => model.Number1) </p>
}
else
{
<p> Not Available</p>
}
</div>
<div class="column">
<p style="font-weight: 700;"> Number2 </p>
#if ((Model.Number2 != null))
{
<p> #Html.DisplayFor(model => model.Number2) </p>
}
else
{
<p> Not Available</p>
}
</div>
<div class="column">
<p style="font-weight: 700;"> Number3 </p>
#if ((Model.Number3 != null))
{
<p> #Html.DisplayFor(model => model.Number3) </p>
}
else
{
<p> Not Available</p>
}
</div>
<div class="column">
<p style="font-weight: 700;"> Number4 </p>
#if ((Model.Number4 != null))
{
<p> #Html.DisplayFor(model => model.Number4) </p>
}
else
{
<p> Not Available</p>
}
</div>
<div class="column">
<p style="font-weight: 700;"> Number5 </p>
#if ((Model.Number5 != null))
{
<p> #Html.DisplayFor(model => model.Number5) </p>
}
else
{
<p> Not Available</p>
}
</div>
</div>

Related

pass result ajax to blade with foreach

i am trying to pass the ajax response to my view and use it as a variable to foreach,I need it to update the quantity of bikes available on the dates selected by the user
the procedure I use is:
I take the selected data in the calendar, I pass them via ajax to my controller
from the controller I execute the queries on the database and return to ajax a json with the data.
the ajax data must be cycled to assign the corresponding quantities to the categories but I don't know how to pass this data to the view
my view
#foreach ($category as $cat)
<div class="col pb-5 m-1">
<?php
$categoryId=DB::table('categories')->select('id')->orderBy('id', 'asc')->get();
foreach ($categoryId as $key) {
$quantity[$key->id]=DB::table('bikes')->where('category_id','=',$key->id)->count('*');
}
?>
<div class="card cat m-auto position-relative " id="cat{{$cat->id}}" >
#foreach ($qty as $item=>$val)
#if ($item==$cat->id)
<p class="m-3" id="numberqty" style="font-weight: bold;color:#ce2e30;text-shadow: 2px 5px 3px rgba(150, 150, 150, 0.92);">{{-- x{{$val}} --}}</p>
#endif
#endforeach
<p class="check position-absolute" style="display: none"><i class="fa fa-check" aria-hidden="true"></i></p>
<input class="cat-id" type="number" value="{{$cat->id}}" hidden>
<input class="id-cat" type="checkbox" name="category[]" id="category" value="{{$cat->id}}" hidden>
<img class="card-img-top p-3" src="{{asset('storage/'.$cat->cover_image)}}" alt="">
<div class="card-body my-n3">
<h3 class="card-title text-center" style="text-shadow: 2px 5px 3px rgba(150, 150, 150, 0.92);">{{$cat->tipo}}</h3>
{{-- <h3 class="card-title">Disponibilità: {{$val}}</h3> --}}
<button class="btn btn-primary pl-5 pr-5 ml-5 drop" type="button">{{__('payment.page.price')}}</button>
<button class="btn btn-primary pl-5 pr-5" type="button">Dettagli</button>
<div class="show-drop" style="display: none">
<h3 class="text-center my-1">{{__('payment.page.price')}}</h3>
<p class="text-center"> {{__('payment.page.1day')}} {{$cat->base}} </p> <hr>
<p class="text-center"> {{__('payment.page.2day')}} {{$cat->twoDay}}</p> <hr>
<p class="text-center"> {{__('payment.page.3day')}} {{$cat->threeDay}}</p> <hr>
<p class="text-center"> {{__('payment.page.4day')}} {{$cat->fourDay}}</p> <hr>
<p class="text-center"> {{__('payment.page.5day')}} {{$cat->fiveDay}}</p> <hr>
<p class="text-center"> {{__('payment.page.6day')}} {{$cat->sixDay}}</p> <hr>
<p class="text-center"> {{__('payment.page.7day')}} {{$cat->sevenDay}}</p>
<p class="text-center"> {{$cat->overprice}} {{__('payment.page.overprice')}}</p>
{{-- <p>{{$cat->overprice}}</p> --}}
</div>
</div>
</div>
<div class="number-drop" style="display: none">
<label for="quantity{{$cat->id}}">Nome</label>
<input name="{{$cat->id}}" type="number" id="quantity{{$cat->id}}" class="form-control" value="0" >
</div>
</div>
#endforeach
my ajax
$('#range_date').on('change', function(){
var data = $(this).val();
var split = data.split(' - ');
var startDate = split[0];
var dayStart = startDate.substr(0,2);
var monthStart = startDate.substr(3,2);
var yearStart = startDate.substr(6,4);
var startCorrect = monthStart+"/"+dayStart+"/"+yearStart;
console.log(startCorrect);
var endDate = split[1];
var dayEnd = endDate.substr(0,2);
var monthEnd = endDate.substr(3,2);
var yearEnd = endDate.substr(6,4);
var endCorrect = monthEnd+"/"+dayEnd+"/"+yearEnd;
console.log(endCorrect);
var date1 = new Date(startCorrect);
var date2 = new Date(endCorrect);
var diffTime = Math.abs(date2 - date1);
var diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
$.ajax({
"url": "bookingCheck",
"data": {
"start": startCorrect,
"end":endCorrect
},
"method": "GET",
success: function (response) {
let res = response;
let qty = res['qty'];
console.log(qty);
document.getElementById('numberqty').innerHTML=qty;
$('#numberqty').html(qty.html);
}
});
});
my controller
public function checkBike(Request $request){
$date1=Carbon::parse($request->start)->format('Y-m-d');
$date2=Carbon::parse($request->end)->format('Y-m-d');
$contract=DB::table('contracts')->get();
$contractdate=DB::table('contracts')->whereRaw('? between data_inizio and data_fine', [$date1,$date2])->get();
if (count($contractdate) > 0) {
foreach ($contractdate as $key) {
$id=$key->id;
}
$bikeContract=DB::table('bike_contract')->where('contract_id','=',$id)->get();
foreach ($bikeContract as $key) {
$bikeselect[$key->id]=DB::table('bikes')->where('id','=',$key->bike_id)->get();
}
foreach ($bikeselect[$key->id] as $key) {
$idcat=$key->category_id;
$quantity=DB::table('bikes')->select('category_id')->whereNotIn('category_id',[$idcat])->get();
}
foreach ($quantity as $key) {
$qty[$key->category_id]=DB::table('bikes')->where('category_id','=',$key->category_id)->count('*');
}
return response()->json(["qty"=>$qty]);
} else {
$categoryId=DB::table('categories')->select('id')->orderBy('id', 'asc')->get();
foreach ($categoryId as $key) {
$quantity[$key->id]=DB::table('bikes')->where('category_id','=',$key->id)->count('*');
}
return response()->json(["qty"=>$quantity]);
}
}
}
Try this:
success: function (response) {
response = JSON.parse(response);
let qty = response.qty;
}

how to hide and check a radio button if condition is true

Hy developers pls i have a vuejs code that i would love the radio checked if row.callback_phone starts with 05 or hide the div if callback_phone number is empty. pls my code is below.
<div class="row space" >
<div class="col-md-1">
<input type="radio" name="inp" :value="row.calling_no" aria-selected="true" :checked="checkcall" :disabled="checkInputFunction">
</div>
<div class="col-md-11">
<label class="mol">שלח למספר שממנו חייגו ({{ row.calling_no}})</label>
</div>
</div>
<div class="row space" >
<div class="col-md-1">
<input type="radio" name="inp" :value="row.callback_phone" :checked="checkback" :disabled="checkInputFunction2" >
</div>
<div class="col-md-11">
<label class="mol" >שלח למספר שהלקוח השאיר ({{ row.callback_phone}})</label>
</div>
</div>
my script is below
<script>
export default {
name: "MailModalComponent",
props: {
row: {
type: Object,
default: () => ({}),
}
},
data() {
return {
set_token: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
pageUrl: window.pageUrl,
}
},
computed:{
checkcall() {
if (this.row.callback_phone.substring(0, 2) == '05') {
return true;
} else {
return false;
}
},
checkback() {
if (this.row.calling_no.substring(0, 2) == '05') {
return true;
} else {
return false;
}
},
checkInputFunction(){
if(Object.keys(this.row).length > 0){
if(this.row.calling_no == '' ||this.row.calling_no == 'Null' ||
this.row.calling_no?
this.row.calling_no.substring(0,2)!='05':true){
return true;
}else{
return false;
}
}
},
checkInputFunction2(){
if(Object.keys(this.row).length > 0){
if(this.row.callback_phone == '' ||this.row.callback_phone == 'Null' ||
this.row.callback_phone?
this.row.callback_phone.substring(0,2)!='05':true){
return true;
}else{
return false;
}
}
}
},
methods: {
submitToWhatsapp(e) {
e.preventDefault();
},
}
}
i just updated this code, i am fetching the data from my database, but i want conditionally render elements as stated above, please i need help.
Your code worked fine for me. I've included a snippet below with a <input type="text /> to let you change row.callback_phone, then when you type a value starting with 05 the radio button becomes checked.
You can use v-if="row.calling_no && row.calling_no.length" or v-if="row.callback_no && row.callback_no.length" on a div to hide it.
Take a look at the documentation for conditional rendering.
I've added another computed for checkAnyButNotBoth.
new Vue({
el: "#app",
data: () => {
return {
row: {
callback_phone: "",
calling_no: ""
}
}
},
computed: {
checkcall() {
return this.row.calling_no.substring(0, 2) == '05';
},
checkback() {
return this.row.callback_phone.substring(0, 2) == '05';
},
checkAnyButNotBoth() {
return this.checkcall ? !this.checkback : this.checkback;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div id="app">
<div class="row space">
<div class="col-md-1">
<input type="radio" :checked="checkcall" v-if="row.calling_no && row.calling_no.length">
</div>
<div class="col-md-11">
<label class="mol">Calling No: ({{ row.calling_no}})</label>
<input type="text" v-model="row.calling_no" />
</div>
</div>
<div class="row space">
<div class="col-md-1">
<input type="radio" :checked="checkback" v-if="row.callback_phone && row.callback_phone.length">
</div>
<div class="col-md-11">
<label class="mol">Callback Phone: ({{ row.callback_phone}})</label>
<input type="text" v-model="row.callback_phone" />
</div>
</div>
<div class="row">
<div class="col-12">
calling_no starts with 05: {{checkcall}}
</div>
<div class="col-12">
callback_phone starts with 05: {{checkback}}
</div>
<div class="col-12">
either but not both start with 05: {{checkAnyButNotBoth}}
</div>
</div>
</div>

Angular 2: Enable button when form is updated

I want to enable a button if at least one field in the form is updated, but when I input some changes in my textarea, the button remains disabled.
I have 3 items in my form - Input Field, Multiple Select Dropdown, Textarea
The button enables when there are changes in the input field or multiple select dropdown, but when I change something in the textarea, it won't enable. Maybe there's something wrong with the for loop and the breaks
Here are my codes:
if (this.data.process == "update") {
for(const f in this.categoryForm.value){
console.log(this.categoryForm.value);
if (f == "categorytags"){
let categorytagsArray = [];
let categorytagsFormArray = this.categoryForm.value[f];
for (const x in this.data.category[f]) {
categorytagsArray.push(this.data.category[f][x]._id);
}
if (categorytagsArray.length != categorytagsFormArray.length) {
this.disableButton = false;
break;
} else {
for (const i in categorytagsFormArray) {
if (categorytagsArray.indexOf(categorytagsFormArray[i]) == -1) {
this.disableButton = false;
break;
} else {
this.disableButton = true;
}
}
}
break;
}
else {
if (this.categoryForm.value[f] == this.data.category[f]) {
this.disableButton = true;
} else {
this.disableButton = false;
break;
}
}
}
}
<div class="dialog-form">
<div class="header">{{data.title}}</div>
<div class="content">
<form class="ui form" [formGroup]="categoryForm" *ngIf="categoryForm" novalidate>
<div class="field required" [class.error]="formErrors.name">
<label>Name</label>
<input type="text" formControlName="name" placeholder="Enter Name..." maxlength="100">
<div *ngIf="formErrors.name" class="field-error">
{{ formErrors.name }}
</div>
</div>
<div class="field required" [class.error]="formErrors.categorytags">
<label>Category Tag</label>
<select name="categorytags" id="categorytags" class="ui fluid dropdown" formControlName="categorytags" multiple="">
<option [attr.value]=categoryTag._id *ngFor="let categoryTag of categorytags">{{ categoryTag.name }}</option>
</select>
<div *ngIf="formErrors.categorytags" class="field-error">
{{ formErrors.categorytags }}
</div>
</div>
<div class="field">
<label>Remarks</label>
<textarea rows="6" formControlName="remark" maxlength="1000"></textarea>
</div>
</form>
</div>
<div class="actions">
<button class="ui basic button" (click)="cancel()">Cancel</button>
<button class="ui primary button" [disabled]="disableButton" (click)="save()">{{data.process.charAt(0).toUpperCase() + data.process.slice(1)}}</button>
</div>
</div>

Previous content of partial view not deleting after return from ajax call

I'm trying to update partialview after ajax call, the partial view is updating but the previous content not deleted from screen.
I have now the prevoious one and the current results on the screen.
That's my code:
public ActionResult FindMovies(string text)
{
ViewBag.ShowButton = Rented;
FindMovie(text);
if (movies.Count == 0)
ViewBag.Movies = "null";
else
ViewBag.Movies = "notNull";
return View(movies);
}
public ActionResult Rent(int id)
{
if (Rented.Equals("no"))
{
movieRent = db.Movies.Find(id);
movieRent.UserRent = userId;
movieRent.Rented = true;
db.Entry(movieRent).State = EntityState.Modified;
db.SaveChanges();
Rented = "yes";
movies.Find(x => x.ID == id).UserRent = userId;
movies.Find(x => x.ID == id).Rented = true;
}
return PartialView("MovieList", movies);
}
That's the view:
<div class="center">
#{Html.RenderPartial("MovieList", Model);}
</div>
and its the partialview:
#model IEnumerable<MvcMovies.Models.Movies>
<ul class="result">
#foreach (var item in Model)
{
<li>
<table>
<tr>
<th>
<figure>
<img src="#Url.Content(#item.Path)"
width="100" height="100" alt="movie logo" />
</figure>
</th>
<th>
<article>
<div class="editor-label">
#Html.DisplayFor(modelItem => item.Name)
</div>
<div class="editor-label">
#Html.DisplayFor(modelItem => item.Year)
</div>
<div class="editor-label">
#Html.DisplayFor(modelItem => item.StageManager)
</div>
<div class="editor-label">
#Html.DisplayFor(modelItem => item.Ganre)
</div>
<div class="editor-label">
#Html.DisplayFor(modelItem => item.Summary)
</div>
<div class="rent" id="rent">
#if (item.Rented.Equals(true))
{
<label>Rented</label>
}
else
{
#Ajax.ActionLink("Rent",
"Rent",
"Subscription",
new { id = item.ID },
new AjaxOptions()
{
UpdateTargetId = "rent",
OnComplete = "onAjaxComplete",
HttpMethod = "post",
})
}
</div>
</article>
</th>
</tr>
</table>
</li>
}
</ul>
Thanks.

Delete page not showing selected record

This is homework, an ASP.NET MVC and Web forms Web application using a repository (with data hard coded and no database) to rate doctors. The user should be able to edit and delete records, but when the application is run, and the "Delete" link is pressed for one of the records, the Delete page does not show the details of that record. Why not?
Here are the Delete methods:
public ActionResult Delete(string DoctorPicture)
{
repo.Remove(DoctorPicture);
return View("Delete");
}
[HttpPost]
public ActionResult Delete(string DoctorPicture, FormCollection collection)
{
try
{
// TODO: Add delete logic here
repo.Remove(DoctorPicture);
return View("Delete");
}
catch
{
return View();
}
}
From repo.Remove(DoctorPicture); it goes here in TestDoctorRepository, and doctor is null. Is it supposed to be?
public void Remove(string DoctorPicture)
{
var doctor = from d in doctors where d.DoctorPicture == DoctorPicture select d;
doctors.Remove(doctor.FirstOrDefault());
}
This is what my list of doctors looks like. Is my path for the images posing a problem?
public TestDoctorRepository()
{
doctors = new List<Doctor> {
new Doctor { DoctorPicture = "Images/0cropped.jpg", DoctorName = "Michael Shores", DoctorSpecialty = "Opthamology", times = 0, rating = 0, rated = true, avg=0, fave = true },
//more doctors
};
}
public Doctor GetDoctorByDoctorPicture(string DoctorPicture)
{
var selectedDoctor = from d in doctors
where d.DoctorPicture == DoctorPicture
select d;
return selectedDoctor.FirstOrDefault();
}
Delete View:
#model MidtermApplication.Models.Doctor
#{
ViewBag.Title = "Delete";
}
<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
<fieldset>
<legend>Doctor</legend>
<div class="display-label">
#Html.DisplayNameFor(model => model.DoctorPicture)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.DoctorPicture)
</div>
<div class="display-label">
#Html.DisplayNameFor(model => model.DoctorName)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.DoctorName)
</div>
<div class="display-label">
#Html.DisplayNameFor(model => model.DoctorSpecialty)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.DoctorSpecialty)
</div>
<div class="display-label">
#Html.DisplayNameFor(model => model.rating)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.rating)
</div>
<div class="display-label">
#Html.DisplayNameFor(model => model.times)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.times)
</div>
<div class="display-label">
#Html.DisplayNameFor(model => model.fave)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.fave)
</div>
<div class="display-label">
#Html.DisplayNameFor(model => model.rated)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.rated)
</div>
</fieldset>
#using (Html.BeginForm()) {
<p>
<input type="submit" value="Delete" /> |
#Html.ActionLink("Back to List", "Index")
</p>
}

Resources