Default value on one of the fields in create view - vb.net

I am trying to set a default value for the scaffold create view that MVC created for me. I have tried creating an instance of the model and passing it to the view but its throwing errors.
Function Create(id As Integer) As ViewResult
Dim job As Job
job.CustomerId = id
Return View(job)
End Function
How would I get my create view to be prepopulated with the id in the parameter using the following view so when a new Job is created it is automatically created with that customer id. My view is below:
#ModelType Laundry.Job
#Code
ViewData("Title") = "Create"
End Code
<h2>Create</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#Using Html.BeginForm()
#Html.ValidationSummary(True)
#<fieldset>
<legend>Job</legend>
<div class="editor-label">
#Html.LabelFor(Function(model) model.JobDate)
</div>
<div class="editor-field">
#Html.EditorFor(Function(model) model.JobDate)
#Html.ValidationMessageFor(Function(model) model.JobDate)
</div>
<div class="editor-label">
#Html.LabelFor(Function(model) model.CustomerId)
</div>
<div class="editor-field">
#Html.EditorFor(Function(model) model.CustomerId)
#Html.ValidationMessageFor(Function(model) model.CustomerId)
</div>
<div class="editor-label">
#Html.LabelFor(Function(model) model.BillId)
</div>
<div class="editor-field">
#Html.EditorFor(Function(model) model.BillId)
#Html.ValidationMessageFor(Function(model) model.BillId)
</div>
<div class="editor-label">
#Html.LabelFor(Function(model) model.JobStatus)
</div>
<div class="editor-field">
#Html.EditorFor(Function(model) model.JobStatus)
#Html.ValidationMessageFor(Function(model) model.JobStatus)
</div>
<div class="editor-label">
#Html.LabelFor(Function(model) model.JobAmount)
</div>
<div class="editor-field">
#Html.EditorFor(Function(model) model.JobAmount)
#Html.ValidationMessageFor(Function(model) model.JobAmount)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
End Using
<div>
#Html.ActionLink("Back to List", "Index")
</div>
I don't necessarily even need to show the customer id on the form but that new object needs to be created with the parameter passed to the controller and the rest of the info the user chooses.

Method 1 : If you want to show the customerId, then you can use the following code...
<div class="editor-label">
#Html.LabelFor(Function(model) model.CustomerId)
</div>
This way, the CustomerId will be displayed, user cannot change it and when postback is done, this value is still present as a part of the model.
Method 2 : If you dont want to display, but still use it for the above purpose, then use the code written below...
<div class="editor-label">
#Html.HiddenFor(Function(model) model.CustomerId)
</div>
Hope this is what you wanted.

Related

The Laravel 8 crud that uses the modal does not add data to the database

I work on one project for college and I have one problem...Does anyone know why I don't want to enter data into the database after adding by modal method. It is also not updated. And it doesn’t throw out a single mistake. Namely, I would like to have a crud operation on the same page, ie not to switch to another url when clicking on edit, add ... Just to add that the delete button is the only one of these three ...
index.blade.php
<?php
use App\Models\User;
use App\Models\Client;
use App\Models\Event;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap CRUD Data Table for Database with Modal Form</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto|Varela+Round">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<body>
<div class="container">
<div class="table-wrapper">
<div class="table-title">
<div class="row">
<div class="col-sm-6">
<h2>Uredi <b>klijente</b></h2>
</div>
<div class="col-sm-6">
<i class="material-icons"></i> <span>Dodaj novog klijenta</span>
</div>
</div>
</div>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Ime</th>
<th>Prezime</th>
<th>Datum rođenja</th>
<th>Email roditelja</th>
<th>Tel.roditelja</th>
<th>U terapiji?</th>
<th>Dijagnoza</th>
<th>Komentar</th>
<th>Logoped</th>
<th>Akcije</th>
</tr>
</thead>
<tbody>
#foreach($clients as $client)
<tr>
<td>{{$client->name}}</td>
<td>{{$client->lastname}}</td>
<td>{{$client->date_of_birth}}</td>
<td>{{$client->email}}</td>
<td>{{$client->telephone}}</td>
<td>{{$client->in_therapy}}</td>
<td>{{$client->diagnosis}}</td>
<td>{{$client->comments}}</td>
<td>{{$client->therapists_id}}</td>
<td>
<i class="material-icons" data-toggle="tooltip" title="Edit"></i>
<i class="material-icons" data-toggle="tooltip" title="Delete"></i>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
<!-- add Modal HTML -->
<div id="addEmployeeModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form>
<div class="modal-header">
<h4 class="modal-title">Dodaj klijenta</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
{!! Form::open(['action' =>['ClientsController#store',''],'method'=>'POST','style'=>'width:50%',]) !!}
{{csrf_field()}}
<div class="modal-body">
<div class="form-group">
{{Form::label('name','Ime')}}
{{Form::text('name','',['class'=>'form-control'])}}
</div>
<div class="form-group">
{{Form::label('lastname','Prezime')}}
{{Form::text('lastname','',['class'=>'form-control'])}}
</div>
<div class="form-group">
{{Form::label('date_of_birth','Datum rođenja')}}
{{Form::date('date_of_birth','',['class'=>'form-control'])}}
</div>
<div class="form-group">
{{Form::label('email','Email roditelja')}}
{{Form::text('email','',['class'=>'form-control'])}}
</div>
<div class="form-group">
{{Form::label('telephone','Tel. roditelja')}}
{{Form::text('telephone','',['class'=>'form-control'])}}
</div>
<div class="form-group">
{{Form::label('in_therapy','U terapiji?')}}<br/>
{{Form::checkbox('in_therapy','Da',['class'=>'form-control'])}}Da<br/>
{{Form::checkbox('in_therapy','Ne',['class'=>'form-control'])}}Ne<br/>
</div>
<div class="form-group">
{{Form::label('diagnosis','Dijagnoza')}}
{{Form::textarea('diagnosis','',['class'=>'form-control','rows' => 3, 'cols' => 170,])}}
</div>
<div class="form-group">
{{Form::label('comments','Komentari')}}
{{Form::textarea('comments','',['class'=>'form-control','rows' => 3, 'cols' => 170,])}}
</div>
<div class="form-group">
{{Form::label('user_id', 'Logoped')}}<br/>
{{Form::select('user_id', $sp_therapist, null, ['class' => 'form-control','placeholder' => 'Izaberite logopeda'])}}
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Odustani">
<input type="submit" class="btn btn-success" value="Dodaj">
</div>
{!!Form::close()!!}
</div>
</div>
</div>
<!-- Edit Modal HTML -->
<div id="editEmployeeModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form>
<div class="modal-header">
<h4 class="modal-title">Edit Employee</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
{!! Form::open(['action' =>['ClientsController#update',''],'method'=>'POST','style'=>'width:50%',]) !!}
{{csrf_field()}}
<div class="modal-body">
<div class="form-group">
{{Form::label('name', 'Ime')}}
{{Form::text('name', $client->name, ['class' => 'form-control'])}}
</div>
<div class="form-group">
{{Form::label('lastname', 'Prezime')}}
{{Form::text('lastname', $client->lastname, ['class' => 'form-control', 'placeholder' ])}}
</div>
<div class="form-group">
{{Form::label('date_of_birth', 'Datum rođenja')}}
{{Form::date('date_of_birth', $client->date_of_birth, ['class' => 'form-control', 'placeholder' => 'Unesite datum rođenja djeteta'])}}
</div>
<div class="form-group">
{{Form::label('email', 'Email')}}
{{Form::text('email', $client->email, ['class' => 'form-control', 'placeholder' => 'Unesite email roditelja'])}}
</div>
<div class="form-group">
{{Form::label('telephone', 'Kontakt broj:')}}
{{Form::text('telephone', $client->telephone, ['class' => 'form-control', 'placeholder' => 'Unesite kontakt broj'])}}
</div>
<div class="form-group">
#if($client->in_therapy != 1)
<div class="form-group">
{{Form::label('in_therapy', 'U terapiji')}}<br>
#if($client->in_therapy == "Da")
{{Form::checkbox('in_therapy', 'Da',$client->in_therapy)}} Da <br>
{{Form::checkbox('in_therapy', 'Ne','')}} Ne<br>
#elseif($client->in_therapy == "Ne")
{{Form::checkbox('in_therapy', 'Da',)}} Da<br>
{{Form::checkbox('in_therapy', 'Ne',$client->in_therapy)}} Ne <br>
#endif
</div>
</div>
#else
<div class="form-group">
{{Form::label('in_therapy', 'U terapiji?')}}<br>
#if($client->in_therapy == "Da")
{{Form::text('in_therapy',$client->in_therapy,['class'=>'form-control','readonly '])}} <br>
#elseif($client->in_therapy == "Ne")
{{Form::text('in_therapy',$client->in_therapy,['class'=>'form-control','readonly '])}} <br>
</div>
#endif
<div class="form-group">
{{Form::label('in_therapy', 'U terapiji?')}}<br>
#if($client->in_therapy == "Da")
{{Form::text('in_therapy',$client->in_therapy,['class'=>'form-control','readonly '])}} <br>
#elseif($client->in_therapy == "Ne")
{{Form::text('in_therapy',$client->in_therapy,['class'=>'form-control','readonly '])}} <br>
</div>
#endif
#endif
<div class="form-group">
{{Form::label('diagnosis', 'Dijagnoza?')}}<br/>
{{Form::textarea('diagnosis', $client->diagnosis, ['class' => 'form-control', 'rows' => 5, 'cols' => 170])}}
</div>
<div class="form-group">
{{Form::label('comments', 'Komentari')}}<br/>
{{Form::textarea('comments', $client->comments, ['class' => 'form-control', 'rows' => 5, 'cols' => 170, 'placeholder' => 'Unesite popratne komentare'])}}
</div>
<div class="form-group">
{{Form::label('therapists_id', 'Logoped')}}
{{Form::select('therapists_id', $sp_therapist, $client->therapists_id,['class' => 'form-control', 'placeholder' => 'Izaberite logopeda'])}}
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
<input type="submit" class="btn btn-info" value="Save">
</div>
{!!Form::close()!!}
</div>
</div>
</div>
<!-- Delete Modal HTML -->
<div id="deleteEmployeeModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
{!!Form::open(['action' =>['ClientsController#destroy', $client->id], 'method' => 'POST'])!!}
<div class="modal-header">
<h4 class="modal-title">Izbriši klijenta</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p>Da li ste sigurni da želite izbrisati ovog klijenta?</p>
<p class="text-warning"><small style="color: #000">Ova akcija se ne može poništiti</small></p>
</div>
<div class="modal-footer">
#method('DELETE')
<input type="button" class="btn btn-default" data-dismiss="modal" value="Odustani">
<input type="submit" class="btn btn-danger" value="Izbriši">
</div>
{!!Form::close()!!}
</div>
</div>
</div>
</body>
</html>
#endsection
this is controller for store and edit.
public function store(Request $request)
{
$this->validate($request,[
'name' => 'required',
'lastname' => 'required',
'date_of_birth' => 'required',
'telephone' => 'required'
]);
$client = new Client;
$client->name = $request->input('name');
$client->lastname = $request->input('lastname');
$client->date_of_birth = $request->input('date_of_birth');
$client->email = $request->input('email');
$client->telephone = $request->input('telephone');
$client->in_therapy = $request->input('in_therapy');
$client->diagnosis = $request->input('diagnosis');
$client->comments = $request->input('comments');
$client->therapists_id = $request->input('user_id');
$client->save();
return redirect('/clients')->with('success', 'Klijent je unesen');
}
public function edit($id)
{
$sp_therapist = DB::table('users')->pluck('name', 'id');
$client = Client::find($id);
return view('clients.edit')->with('client',$client)->with('sp_therapist', $sp_therapist);
}
and this is web.php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FullCalenderController;
use App\Http\Controllers\Auth\RegisterController;
Auth::routes();
Route::group(['middleware' => 'auth'], function () {
Route::get('/','PagesController#index');
Route::get('/dashboard', 'DashboardController#index')->name('dashboard');
Route::get('/register', 'Auth\RegisterController#create')->name('register');
Route::resource('clients','ClientsController');
//CALENDAR
Route::get('schedule', [FullCalenderController::class, 'index']);
Route::post('schedule/action', [FullCalenderController::class, 'action']);
});
thanks
Check that the Modals you're using have the $fillable property with the values you want to insert, something like this:
class User extends Model {
protected $fillable = ['name', 'lastname', 'email']
}
otherwise Eloquent doesn't allow you to inject the inputs.
first if u use laravel 8 use this on ur web.php
use App\Http\Controllers\ClientsController;
Route::resource('clients',[ClientsController::class]);
and in ur index file set form action to route('clients.store') , use route name
in ur store controller try to dd($request) to see the respond, if u still have any problem, let us know

When i click on tab i lose data and code not looping throw Model again?

Hi
i have try to loop throw data in "Categories" Table and it works - i got data when i open View in first time but if i click on a tab to see its content i got only first record ?
i don't know why i lose all data i got in first time ?
Razor Code:
#section personAds{
<h2 class="title text-center">Person Ads</h2>
<div class="col-sm-12">
<ul class="nav nav-tabs">
<li class="active">Home</li>
<li>Cars</li>
</ul>
</div>
<div class="tab-content">
#foreach (var personItems in Model.Where(isCompany => isCompany.isCompany == false))
{
<div class="tab-pane fade active in" id="propertytab">
<div class="col-sm-3">
<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfoslide text-center">
<img src="#Url.Content(personItems.catImage)" alt="" />
<h4>#personItems.catName</h4>
<i class="#personItems.classIcon"></i>More
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane fade" id="carstab">
<div class="col-sm-3">
<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfoslide text-center">
<img src="#Url.Content(personItems.catImage)" alt="" />
<h4>#personItems.catName</h4>
<i class="#personItems.classIcon"></i>More
</div>
</div>
</div>
</div>
</div>
}
</div>
}
Controller Code:
public ActionResult Contact()
{
var model = _db.Categories.ToList();
return View(model);
}
and i try to remove where condition and i got same result - when i click on any tab i got only first record ?!
Please see the Video of Problem ... Click Here
From the look of your code I think you have simply got your 'foreach' in the wrong position.
It looks like you are creating repeated 'tab' DIV's which will each have just one record in.
This is probably somewhat better, notice I have moved the 'propertytab' outside of the #foreach
<div class="tab-pane fade active in" id="propertytab">
#foreach (var personItems in Model.Where(isCompany => isCompany.isCompany == false))
{
<div class="col-sm-3">
<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfoslide text-center">
<img src="#Url.Content(personItems.catImage)" alt="" />
<h4>#personItems.catName</h4>
<i class="#personItems.classIcon"></i>More
</div>
</div>
</div>
</div>
}
</div>
<div class="tab-pane fade" id="carstab">
#foreach (var personItems in Model.Where(isCompany => isCompany.isCompany == false))
<div class="col-sm-3">
<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfoslide text-center">
<img src="#Url.Content(personItems.catImage)" alt="" />
<h4>#personItems.catName</h4>
<i class="#personItems.classIcon"></i>More
</div>
</div>
</div>
</div>
}
</div>

submit inside partial view - mvc4

How can i trigger the submit button from partial view without using Html.BeginForm tag in Partial View. Reason being when there are two form tags, that is in main view and partial view, the validation doesn't work.
The important thing is that I want the validation to work.
My Partial View code:
<div id="AddMe">
<div class="row">
#Html.LabelFor(model => model.FirstName)
#Html.TextBoxFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName) // this should work
</div>
</div>
<div>
<input name="submit" type="submit" id="submit" value="Save" /> // how do i trigger this from partial view
</div>
My Main View code:
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post))
{
<div class="modal" id="modalId" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body" id="modalbodyId">
#Html.Partial("PartilViewName")
</div>
<div class="modal-header">
<button type="submit">
</div>
</div>
</div>
</div>
}
For Validation purpose, I have added the following lines of code in Main View.
$("#modalId").click(function () {
var form = $("#modalbodyId").closest("form");
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(form);
$.ajax({
url: "/ControllerName/ActionName",
type: "POST",
data: $("#modalbodyId").serialize(),
cache: false
});
});
Also just for the records all the models and other Annotations are in place.
Note: Do i need to add the unobtrusive/ajax code inside Partial View.

HttpPost doesn't work into Modal Popup in MVC 4

I have view that has CompanyTable partial view. So this partial view has a CreateBankAccount partial view. Last partial view codes are
#model Invoice.Model.BankAccount
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Launch demo modal
<div id="#Model.TaxID" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
#using (Ajax.BeginForm("CreateModal", "CompanyController", new AjaxOptions { UpdateTargetId = "modal", HttpMethod = "post" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>BankAccount</legend>
#Html.HiddenFor(model => model.ID)
<div class="editor-label">
#Html.LabelFor(model => model.BankName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.BankName)
#Html.ValidationMessageFor(model => model.BankName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CorrespondentAccount)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CorrespondentAccount)
#Html.ValidationMessageFor(model => model.CorrespondentAccount)
</div>
<input type="submit" value="save" />
</fieldset>
}
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<input type="submit" class="btn btn-primary" value=" Save changes" data-dismiss="modal" />
</div>
</div>
so this partial view is modal popup. My problem is that when I want to creat bankAccount my HttpPost method doesn't work, and I return Index action. How I can fix it?

Without editor field item not saving

I am trying to let a user create an object and save it to the database. I have scaffolded it all correctly etc and have modified my control to the following:
Function Create(id As Integer) As ViewResult
ViewBag.id = id
Dim job As Job = New Job
job.CustomerId = id
job.JobAmount = 0
job.JobDate = Date.Now()
job.JobStatus = "Active"
Return View(job)
End Function
This then returns the following view:
#ModelType Laundry.Job
#Code
ViewData("Title") = "Create"
End Code
<h2>Create</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#Using Html.BeginForm()
#Html.ValidationSummary(True)
#<fieldset>
<legend>Job</legend>
<div class="editor-label">
#Html.LabelFor(Function(model) model.JobDate)
</div>
<div class="editor-field">
#Html.EditorFor(Function(model) model.JobDate)
#Html.ValidationMessageFor(Function(model) model.JobDate)
</div>
<div class="editor-label">
#Html.LabelFor(Function(model) model.BillId)
</div>
<div class="editor-field">
#Html.EditorFor(Function(model) model.BillId)
#Html.ValidationMessageFor(Function(model) model.BillId)
</div>
<div class="editor-label">
#Html.LabelFor(Function(model) model.CustomerId)
</div>
<div class="editor-field">
#Html.EditorFor(Function(model) model.CustomerId)
#Html.ValidationMessageFor(Function(model) model.CustomerId)
</div>
<div class="editor-label">
#Html.LabelFor(Function(model) model.JobStatus)
</div>
<div class="editor-field">
#Html.EditorFor(Function(model) model.JobStatus)
#Html.ValidationMessageFor(Function(model) model.JobStatus)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
End Using
<div>
#Html.ActionLink("Back to List", "Index")
</div>
I created a instance of job and passed it through the controller to the view in order to default certain values. Specifically I need to create a job object with the id passed to the controller but I do not want the user to be able to edit this id (they should not see this). I thought that if I simply deleted the following from my view:
<div class="editor-label">
#Html.LabelFor(Function(model) model.CustomerId)
</div>
<div class="editor-field">
#Html.EditorFor(Function(model) model.CustomerId)
#Html.ValidationMessageFor(Function(model) model.CustomerId)
</div>
The object would still save with the customerId I set in my controller however it seems if I delete this code when it saves it saves the customerid as 0 and when its there it works correctly but the user can see and edit it.
Am I doing this correctly?
I do not want the user to be able to edit this id (they should not see this)
Use #Html.HiddenFor(Function(model) model.CustomerId) for this. It will persist the value from view to controller, but not be visible to the user.