How to update a table row by passing data from a Bootstrap modal form - spring-boot

I'm fresh in web development and I'm facing some problems
I have an html page that displays a table. Each row contains data and an "edit" button.
What I want is the following:
I already could invoke the modal form and make it pop up with data corresponding to the row's data (through the button "edit") before I add this code to my form tag th:action="#{/countries/update/{id} (id =${countryToUpdate.id})}" and hence I get this following error:
org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'id' cannot be found on null
I know that the passed model attribute countryToUpdateis null
I'm asking if it's possible to pass a model attribute to a the bootstrap modal form
That's my html table:
<table class="table">
<tr>
<th>Id</th>
<th>Description</th>
<th>Capital</th>
<th>Code</th>
<th>Actions</th>
</tr>
<tr th:each="country:${countries}">
<td th:text="${country.id}"></td>
<td th:text="${country.description}"></td>
<td th:text="${country.capital}"></td>
<td th:text="${country.code}"></td>
<td>
<!--Edit button to invoke the bootstrap form-->
<div class="btn-group">
<a th:href="#{/countries/findById/{id} (id=${country.id})}" class="btn btn-primary editModalBtn" data-toggle="modal" data-target="#editModal">Edit</a>
</div>
</td>
</tr>
</table>
The bootstrap form:
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">New message</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<!--the action attribute of the from indicates to where the form is gonna be submitted-->
<form th:action="#{/countries/update/{id} (id =${countryToUpdate.id})}" method="post" th:object="${countryToUpdate}">
<div class="form-group">
<label for="descriptionEdit" class="col-form-label">Description</label>
<!--name should correspond to the fields in the modal class-->
<input
type="text"
class="form-control"
id="descriptionEdit"
name="description"
>
</div>
<div class="form-group">
<label for="capitalEdit" class="col-form-label">Capital</label>
<input type="text"
class="form-control"
id="capitalEdit"
name="capital"
>
</div>
<div class="form-group">
<label for="codeEdit" class="col-form-label">Code</label>
<input type="text"
class="form-control"
id="codeEdit"
name="code"
>
</div>
<div class="form-group">
<label for="continentEdit" class="col-form-label">Continent</label>
<input type="text"
class="form-control"
id="continentEdit"
name="continent"
>
</div>
<div class="form-group">
<label for="nationalityEdit" class="col-form-label">Nationality</label>
<input type="text"
class="form-control"
id="nationalityEdit"
name="nationality"
>
</div>
<div class="modal-footer">
<!--submit type button should be within the form to execute the query-->
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
</div>
</div>
</div>
</div>
My controller:
#GetMapping("countries")
public String findAll(Model model){
List<Country> listOfCountries = countryService.findAll();
model.addAttribute("countries", listOfCountries);
return "country";
}
#GetMapping("countries/findById/{id}")
#ResponseBody
public Country findById(#PathVariable int id, Model mod)
{
Country country = countryService.findById(id).get();
//I want to create a countryToUpdate attribute to use it in the modal form
mod.addAttribute("countryToUpdate", country);
return country;
}
#GetMapping("countries")
public String findAll(Model model){
List<Country> listOfCountries = countryService.findAll();
model.addAttribute("countries", listOfCountries);
return "country";
}
#PostMapping(value="countries/update/{id}")
public String update(#ModelAttribute("countryToUpdate") Country country, #PathVariable int id) {
//Get the country object from database through the passed id
Optional<Country> c = countryService.findById(id);
c.get().setDescription(country.getDescription());
c.get().setContinent(country.getContinent());
c.get().setCode(country.getCode());
c.get().setCapital(country.getCapital());
c.get().setNationality(country.getNationality());
System.out.println("this country description is " + country.getDescription());
countryService.save(c.get());
return "redirect:/countries";
}
Any help would be appreciated.

Related

pass object from HTML template back to the controller

I have the following HTML block. I want to pass the object "jobDTO" back to the contoller "/deleteJob" method. Whatever I do I am getting null object.
<th:block th:if="${jobDTO != null}" th:each="jobDTO: ${allJobDTOs.get(jobGroup)}">
<div id="accordion2" style="margin-bottom: 3px;">
<div class="card" id="headingOne">
<div class="card-header" style="padding: 0">
<h5 class="mb-0">
<button class="btn btn-link" data-toggle="collapse" th:attr="data-target='#accordion2_'+${jobDTO.identity.name}"
aria-expanded="true" aria-controls="collapseChild" >
<p class="font-weight-bold custom-p identity-black" > Job Identity </p>
<p class="custom-p" style="padding-left: 52px;" th:text="${jobDTO.identity.group} +' , ' + ${jobDTO.identity.name}"></p>
</button>
</h5>
</div>
<div th:id="'accordion2_'+${jobDTO.identity.name}" class="collapse" aria-labelledby="headingOne" data-parent="#accordion2">
<div class="card-body">
<dl class="row">
<dt class="col-lg-3">Trigger List</dt>
<dd class="col-sm-9">
<th:block th:each="trigger: ${jobDTO.triggers}">
<p><b>nextFireTime</b> <span th:text="${trigger.nextFireTime}"> </span></p>
<hr>
</th:block>
</dd>
</dl>
<!-- important part.. how to pass the jobDTO object back to the controller -->
<form id="form2" action="#" th:action="#{/deleteJob}" th:object="${jobDTO}" th:method="post">
<input type="text" th:value="*{identity.name}" th:field="*{identity.name}" hidden/>
<button type="submit" value="Submit" class="btn btn-danger btn-sm" >Delete Job</button>
</form>
</div>
</div>
</div>
</div>
</th:block>
my controller relevant parts are:
#GetMapping(value = "/deleteJob")
public String deleteJobPage(Model model) {
model.addAttribute("jobDTO", new ScheduleJobDTO());
//Returns the Home page with the prepared model attributes
return "Home";
}
// =================
#PostMapping("/deleteJob")
public String deleteJob(#ModelAttribute final ScheduleJobDTO jobDTOReturn, BindingResult bindingResult, Model model) {
// I want to receive the jobDTO object here
schedulerService.deleteJobFromGroup(jobDTOReturn.getIdentity().getGroup(),
jobDTOReturn.getIdentity().getName());
return "redirect:/";
}
what I am missing here?
I think there is an error in your input tag, try this :
<input type="text" th:value="${jobDTO.identity.name}" th:field="*{identity.name}" hidden/>

Laravel 5.5 - MethodNotAllowedHttpException

I have an task using Laravel. Which one on my task, user can edit the data on master data table. I'm using modal pop when user want to edit the data. So the user no need to move the page for edit data. On my task I'm using Laravel 5.5
Here is my code :
This is for tabel modal edit
<div class="modal fade" id="edit-modal" tabindex="-1" role="dialog" aria-labelledby="largeModal" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header no-bd">
<h5 class="modal-title">
<span class="fw-mediumbold">Detail</span>
<span class="fw-light">Data</span>
</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form class="form-material form-horizontal" method=post action="{{route('masterdataobjek.update', 'test')}}">
{{ csrf_field() }}
<div class="row">
<div class="col-sm-12">
<input type="hidden" name="id_objek" id="id_objek_modal" value="">
<div class="form-group form-group-default">
<label>Nama Objek</label>
<input id="objek_nama_modal" type="text" name="objek_nama_modal" class="form-control">
</div>
</div>
<div class="col-sm-12">
<div class="form-group form-group-default">
<label for="comment">Deskripsi Objek</label>
<textarea class="form-control" name="objek_desc_modal" id="objek_desc_modal" rows="5"></textarea>
</div>
</div>
<div class="col-sm-12">
<label for="exampleFormControlFile1">Upload WTO File</label>
<div class="form-group form-group-default">
<input type="file" class="form-control-file" name="objek_wto" id="objek_wto">
</div>
</div>
</div>
<div class="modal-footer no-bd">
<button type="submit" class="btn btn-primary">Update</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
For the button clicked code ;
<tbody>
#foreach ($tabelobjek as $ta => $data)
<tr>
<td>{{ $loop->iteration }}</td>
<td>{{ $data->objek_nama}}</td>
<td style="">{{str_limit($data->objek_desc,15)}}</td>
<td>
<div class="form-button-action">
<button type="button" data-toggle="modal"
class="btn btn-link btn-success btn-lg" data-original-title="Edit"
data-target="#edit-modal" id="edit-button"
data-idobjek="{{$data->id_objek}}"
data-namaobjek="{{$data->objek_nama}}"
data-objekdeskripsi="{{$data->objek_desc}}">
<i class="fa fa-edit"></i>
</button>
</div>
</td>
</tr>
#endforeach
</tbody>
for trigger button :
<script>
$(document).ready(function () {
$(document).on('click', '#edit-button', function () {
var namaobjek = $(this).data('namaobjek');
var objekdeskripsi = $(this).data('objekdeskripsi');
var idobjek = $(this).data(idobjek)
$('#id_objek_modal').val(idobjek)
$('#objek_nama_modal').val(namaobjek);
$('#objek_desc_modal').val(objekdeskripsi);
})
})
MasterDataObjekController.php
public function update(Request $request)
{
$updateObjek = TbObjek::findOrFail($request->id_objek);
$updateObjek->update($request->all());
return back();
}
POST requests are for creating new records, PUT and PATCH are for updating records. Refer to the table of HTTP methods on Laravel RESTful containers here
You need to change your form tag from this
<form class="form-material form-horizontal" method=post action="{{route('masterdataobjek.update', 'test')}}">
to this
<form class="form-material form-horizontal" method="put" action="{{route('masterdataobjek.update', 'test')}}">

Getting input from multiple forms by modal in laravel

Im pretty new to web development, im creating basic CRUD for my intern project. My client asked me to make a single create form where i need to upload those input to database, lets say i have 3 table : Shops,Fruits (one shop has many fruits), and Vegetables (one shop has many vegetables)
I ended up making multiple forms, which one main form for the shop input, and some additional form inside modal for fruits and vegetables input (forms are separated).
After submitting and passing to controller, i can only get input from shop form and not the others.
Scripts and styles:
<link rel="stylesheet" href="/css/bootstrap.min.css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//Adding and removing fruit table row
$(".fruit-add").click(function(){
var fruit_pic = $("#fruit_pic").val();
var fruit_pic_name = $("#fruit_pic").val().replace(/C:\\fakepath\\/i, '')
var fruit_name = $("#fruit_name").val();
var markup = "<tr><td>" + fruit_pic_name + "</td><td>" + fruit_name + "</td><td>" + "<button type='button' class='fruit-remove'> Delete </button>" + "</td></tr>";
$(".fruit-table").append(markup);
});
$("body").on("click",".fruit-remove",function(){
$(this).parents("tr").remove();
});
//Adding and removing vegetable table row
$(".vegetable-add").click(function(){
var vegetable_pic = $("#vegetable_pic").val();
var vegetable_pic_name = $("#vegetable_pic").val().replace(/C:\\fakepath\\/i, '')
var vegetable_name = $("#vegetable_name").val();
var markup = "<tr><td>" + vegetable_pic_name + "</td><td>" + vegetable_name + "</td><td>" + "<button type='button' class='vegetable-remove'> Delete </button>" + "</td></tr>";
$(".vegetable-table").append(markup);
});
$("body").on("click",".vegetable-remove",function(){
$(this).parents("tr").remove();
});
});
</script>
My shop form:
<form method="post" action="/add-shop/store" id="addShop" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="shop_name">Shop name</label>
<input type="text" class="form-control" name="shop_name" id="shop_name" aria-describedby="shop_name">
#if($errors->has('shop_name'))
<div class="text-danger">
{{ $errors->first('shop_name')}}
</div>
#endif
</div>
<div class="form-group">
<label> Fruits </label>
<div class="table-responsive">
<table class="table table-bordered table-hover">
<thead class="thead-dark">
<tr>
<th>Picture</th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody class="fruit-table">
</tbody>
</table>
</div>
<!-- Button trigger fruit modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addFruit">
Add fruit
</button>
</div>
<div class="form-group">
<label> Vegetables </label>
<div class="table-responsive">
<table class="table table-bordered table-hover">
<thead class="thead-dark">
<tr>
<th>Picture</th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody class="vegetable-table">
</tbody>
</table>
</div>
<!-- Button trigger vegetable modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addVegetable">
Add vegetable
</button>
</div>
<div class="form-group text-right">
<button type="button" class="btn btn-secondary">Cancel</button>
<button type="submit" class="btn btn-success">Save</button>
</div>
</form>
My forms on popup modal:
<!-- Fruit Modal -->
<div class="modal fade" id="addFruit" tabindex="-1" role="dialog" aria-labelledby="addFruit" aria-hidden="true">
<div class="modal-dialog" role="document">
<form id="form_fruit">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addFruit">Fruit</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label for="fruit_pic">Picture</label>
<input type="file" accept="image/*" name="fruit_pic[]" id="fruit_pic" class="form-control">
</div>
<div class="form-group">
<label for="fruit_name">Name</label>
<input type="text" name="fruit_name[]" class="form-control" id="fruit_name">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary fruit-add" data-dismiss="modal">Add</button>
</div>
</div>
</form>
</div>
</div>
<!-- Vegetable Modal -->
<div class="modal fade" id="addVegetable" tabindex="-1" role="dialog" aria-labelledby="addVegetavle" aria-hidden="true">
<div class="modal-dialog" role="document">
<form id="form_vegetable">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addVegetable">Vegetable</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label for="vegetable_pic">Picture</label>
<input type="file" accept="image/*" name="vegetable_pic[]" id="vegetable_pic" class="form-control">
</div>
<div class="form-group">
<label for="vegetable_name">Name</label>
<input type="text" class="form-control" name="vegetable_name[]" id="vegetable_name" placeholder="Deskripsi">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary vegetable-add" data-dismiss="modal">Add</button>
</div>
</div>
</form>
</div>
</div>
controller functions:
public function add()
{
return view('add-shop');
}
public function storeTest(Request $request)
{
echo "test\n"; //works
echo $request->fruit_name; //doest work
if($request->hasfile('fruit_pic')){ //doesnt work
foreach($request->file('fruit_pic') as $image){
echo $request->fruit_name;
}
}
echo $request->shop_name; //work
}
When i try to submit the form, i get the shop_name but not all the other form attributes (fruits and vegetables)
I have the feeling that my method is not quite right, what is wrong and is there a better way to applicate this?
just taking a quick look at the form you should use at the action
{{url(}}
{{route()}}
your not getting the shop form because the model it self is not in the form make sure to put it in the same form where you submit the original form tag. alternative if you really want to have it outside you can make a hidden input in the form and put there your data in with java script from the model and then submit the form
do this also to the --vegetable modal--:
<!-- Fruit Modal -->
<div class="modal fade" id="addFruit" tabindex="-1" role="dialog" aria-labelledby="addFruit" aria-hidden="true">
<div class="modal-dialog" role="document">
<form id="form_fruit" method="post" action="{{ url('/add-fruits') }}">
{{ csrf_field() }}
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addFruit">Fruit</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label for="fruit_pic">Picture</label>
<input type="file" accept="image/*" name="fruit_pic[]" id="fruit_pic" class="form-control">
</div>
<div class="form-group">
<label for="fruit_name">Name</label>
<input type="text" name="fruit_name" class="form-control" id="fruit_name">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary fruit-add" data-dismiss="modal">Add</button>
</div>
</div>
</form>
</div>
</div>
controller
public function addFruits(Request $request)
{
$this->validate($request, [
'fruit_name' => 'required|string',
'fruit_pic.*' => 'mimes:jpeg,jpg,gif,png,bmp|max:8300',
]);
$fruitname=$request->input('fruit_name');
if($request->hasfile('fruit_pic'))
{
foreach($request->file('fruit_pic') as $file)
{
$name=$file->getClientOriginalName();
$file->move(public_path().'/../../example.com/images', $name);
DB::table('tblfruits')->insert([
'fruit_name' => $fruitname,
'fruit_pic' => $name,
]);
}
}
}
route
Route::post('/add-fruits','Controller#addFruits');

Problem with Passing data from Laravel controller to Boostrap Modal

Hello everyone one i have a problem . I want to pass data from my Controller to my modal . I have a list of categories i want to display it in a dropdown list i've tried using href attribute and ajax but none of these worked is there any solution ?
here is a piece of code :
List of all Categories blade.php :
#extends('layouts.Template')
#section('content')
<div class="content-wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<center> <h2 class="page-title">Gérer les Sous Catégories</h2> </center>
<div class="panel panel-default">
<div class="panel-heading"> <strong>Liste Sous Catégories</strong></div>
<div class="panel-body">
<table id="zctb" class="table table-bordered">
<tr>
<th>Id</th>
<th>Nom</th>
<th>Nom de Catégories</th>
<th>image</th>
<th>created_at</th>
<th>updated_at</th>
<a class="fas fa-plus-circle" style="font-size:60px;color:#e2ccae;margin-left:90%;"href="{{url ('/Sous_Catégories/ajouter')}}"></a>
</tr>
#foreach($Souscategories as $Scategorie)
<tr>
<td>{{$Scategorie->id}}</td>
<td>{{$Scategorie->nom}}</td>
<td>{{$Scategorie ->nomCat}}</td>
<td>{{$Scategorie->image}}</td>
<td>{{$Scategorie -> created_at}}</td>
<td>{{$Scategorie -> updated_at}}</td>
<td ><a class="fas fa-edit" href="{{ route('Sous_Catégories.getAllCategories')}}" data-nom="{{$Scategorie->nom}}" data-nomCat="{{$Scategorie->nomCat}}" data-image="{{$Scategorie->image}}" data-cat_id1 ="{{$Scategorie->id }}" data-toggle="modal" data-target="#edit1">Edit</a></td>
<td><a class="fas fa-trash" href="{{url ('/Sous_Catégories/supp',[$Scategorie->id])}}" > </td>
</tr>
#endforeach
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="edit1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modifier Sous Catégories</h4>
</div>
<form action="{{ route('Sous_Catégories.update','test')}}" method="POST">
{{method_field('patch')}}
{{csrf_field()}}
<div class="modal-body">
<input type="hidden" name="cat_id1" id="cat_id1" value="">
#include('formSousCat')
</div>
<div class="modal-footer">
<button id="fermer" type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>
<button id="save" type="submit" class="btn btn-primary">Enregistrer</button>
</div>
</form>
</div>
</div>
</div>
#endsection
controller Methode :
public function getAllCategories()
{
$Cat = categories::all();
return view('formSousCat', compact('Cat'));
}
My routers :
Route::get('/Sous_Catégories', 'SousCatController#index' );
Route::post('/Sous_Catégories/ajouter', 'SousCatController#create');
Route::get('/Sous_Catégories/supp/{id}', 'SousCatController#destroy');
Route::get('/Sous_Catégories/getAllCategories', 'SousCatController#getAllCategories');
Route::resource('Sous_Catégories', 'SousCatController');
My Modal.blade
<label>Nom</label>
<input id="nom" name="nom" class="form-control"type="text"/>
</div>
<br/>
<div>
<label for="le_nom">Choix de categorie</label><br />
<label for="le_nom">Choix de categorie</label><br />
<select name="le_nom" id="le_nom" class="form-control">
#foreach($Cat as $categorie) <!-- $Cat is undefined -->
<option class="form-control">{{$categorie->nomCat}}</option>
#endforeach
</select>
<div class="input-group">
<div class="custom-file">
<div class="form-group">
<input type="file" name="image" class="form-control-file">
</div>
</div>
You can use a click event on a button tag, to opent the modal and initiate an ajax request which fetches the data from the controller and inserts into the categories.
<button id="openModal">Open Modal</button>
In your controller:
public function getAllCategories()
{
$Cat = categories::all();
return response()->json($cat);
}
In your script
let btn = document.querySelector('#openModal')
let slct = document.querySelector('#le_nom')
btn.addEventListener('click', function(){
$.ajax({
url: '{{url("/Sous_Catégories/getAllCategories")}}',
method: 'GET',
success: function(response){
response.Foreach((op) = > {
slct.innerHTML += `<option value="${op.id}">${op.nomCat}</option>`
})
}
})
})

FormCollection parameter is empty while using #Ajax.BeginForm and html5 controls

I'm developing ASP.NET MVC5 project with boostrap, jquery, jquery UI. Submit is working fine but FormCollection in create Action is arriving empty in HomeController. I don't know what I'm doing wrong or is missing. PLease need help. Below snippet code.
Index.cshtml:
<div class="modal fade" id="modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Empleado</h4>
</div>
<div class="modal-body">
#using (Ajax.BeginForm("Create", "Home", new AjaxOptions() { HttpMethod = "post" }, new { id = "dialog", name = "dialog" }))
{
<div class="panel">
<div class="panel-body">
<div class="form-group">
<label class="control-label">Nombres</label>
<input type="text" class="form-control" id="modalNombres" placeholder="Nombres" />
</div>
<div class="form-group">
<label class="control-label">Apellidos</label>
<input type="text" class="form-control" id="modalApellidos" placeholder="Apellidos" />
</div>
<div class="form-group">
<label class="control-label">Fecha de Nacimiento</label>
<input type="text" class="form-control" id="modalFechaNacimiento" placeholder="Fecha Nacimiento" />
</div>
<div class="form-group">
<label class="control-label">Tipo Documento</label>
<select class="form-control" id="modalTipoDocumento">
<option class="placeholder" selected disabled value="">--- Seleccione ---</option>
#foreach (var item in ViewBag.TiposDocumento)
{
<option value="#item.Id">#item.Descripcion</option>
}
</select>
</div>
<div class="form-group">
<label class="control-label">Número de Documento</label>
<input type="text" class="form-control" id="modalNumeroDocumento" placeholder="Número Documento" />
</div>
</div>
<div class="panel-footer">
<button type="button" role="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" role="button" class="btn btn-primary" id="btnGrabar">Grabar</button>
</div>
</div>
}
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
HomeController is:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
string nombres = collection["modalNombres"];
return RedirectToAction("Index");
}
catch
{
return View();
}
}
None of you <input> elements have name attributes so there is nothing sent to the server. Change
<input type="text" class="form-control" id="modalNombres" placeholder="Nombres" />
to
<input type="text" class="form-control" name="modalNombres" placeholder="Nombres" />
There is no need for id attributes unless you using javascript/jquery to refer to them.
However, I very strongly recommend you go to the MVC site and work through some basic tutorials and learn how to generate a view in MVC. You should have a model, use the strongly typed html helpers to bind to the properties of your model, and the POST method should have a parameter for the model so it is bound (you should never use FormCollection in MVC)
Note also, you using Ajax.BeginForm() which uses ajax to post the form values so return RedirectToAction("Index"); in your POST method is pointless. Ajax calls stay on the same page, they do not redirect.

Resources