my problem is that I made a web page where I can upload image and create a new recipe (filling textboxes), but the submit button does nothing. Any solutions?
#using (Html.BeginForm("Create", "Recipe", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<label for="photo">Upload photo:</label>
<input type="file" name="file" id="file" style="width: 100%;" />
...
<input type="submit" value="Upload" />
}
My Controller look like this:
// GET: Recipe/Create
public ActionResult Create()
{
var userId = User.Identity.GetUserId();
var viewModel = new ReceptDTO
{
Date = DateTime.Now,
UserId = userId
};
return View(viewModel);
}
// POST: Recipe/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ReceptDTO recipe, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
ReceptManager recipes = new ReceptManager();
recipes.SaveRecept(recipe);
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(
Server.MapPath("~/images/recipes/" + User.Identity.GetUserId()), pic);
// File uploaded
file.SaveAs(path);
}
return RedirectToAction("Index", "Home");
}
return View(recipe);
}
EDIT: The full view:
#model Receptura_v4.Models.ReceptDTO
#{
ViewBag.Title = "Új recept feltöltése";
}
<h2>Új recept feltöltése</h2>
#using (Html.BeginForm("Create", "Recipe", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<label for="photo">Fotó feltöltése:</label>
<input type="file" name="file1" id="file1" style="width: 100%;" />
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.Label("Cím:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Adag", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="col-md-3">
#Html.TextBoxFor(model => model.Portion, new { id = "portion", #readonly = "readonly", style = "border:0; color:#f6931f; font-weight:bold;" })
<div id="slider-range-min"></div>
</div>
</div>
</div>
<div class="form-group">
#Html.Label("Elkészítési idő", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="col-md-3">
#Html.TextBoxFor(model => model.Time, new { id = "time", #readonly = "readonly", style = "border:0; color:#f6931f; font-weight:bold;" })
<div id="slider-range-min2"></div>
</div>
</div>
</div>
#*<div class="form-group">
#Html.Label("Elkészítési idő", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Time, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Time, "", new { #class = "text-danger" })
</div>
</div>*#
<div class="form-group">
#Html.Label("Kategória", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Category", new List<SelectListItem>
{
new SelectListItem { Text="Levesek", Value = "Levesek"},
new SelectListItem { Text="Főzelékek", Value = "Főzelékek"},
new SelectListItem { Text="Desszertek", Value = "Desszertek"},
new SelectListItem { Text="Egytálételek", Value = "Egytálételek"}
}, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.Label("Elkészítés", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Preparation, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Preparation, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Nehézség", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="col-md-3">
#Html.TextBoxFor(model => model.Difficulty, new { id = "amount", #readonly = "readonly", style = "border:0; color:#f6931f; font-weight:bold;" })
<div id="slider"></div>
</div>
</div>
</div>
#*<div class="form-group">
#Html.Label("Elkészítési költség", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Price, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Price, "", new { #class = "text-danger" })
</div>
</div>*#
<div class="form-group">
#Html.Label("Elkészítési költség", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="col-md-3">
#Html.TextBoxFor(model => model.Price, new { id = "price", #readonly = "readonly", style = "border:0; color:#f6931f; font-weight:bold;" })
<div id="slider-range-min3"></div>
</div>
</div>
</div>
#Html.HiddenFor(model => model.Date)
#Html.HiddenFor(model => model.UserId)
<div class="form-group">
#Html.Label("Új hozzávaló", htmlAttributes: new { #class = "control-label col-md-2" })
<div>
<input id="Button1" type="button"
value="+" onclick="DynamicDiv();" />
<div id="foo"></div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Feltöltés" />
</div>
</div>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryui")
<script type="text/javascript">
$(function () {
var diff = ["Könnyű", "Közepes", "Nehéz", "Nagyon nehéz"];
$("#slider").slider({
value: 2,
min: 1,
max: 4,
step: 1,
slide: function (event, ui) {
$("#amount").val(diff[ui.value - 1]);
}
});
$("#amount").val("Közepes");
});
</script>
<script type="text/javascript">
$(function () {
$("#slider-range-min2").slider({
range: "min",
value: 5,
min: 1,
max: 100,
slide: function (event, ui) {
$("#time").val(ui.value + " fő");
}
});
$("#time").val($("#slider-range-min2").slider("value") + " fő");
});
</script>
<script type="text/javascript">
$(function () {
$("#slider-range-min").slider({
range: "min",
value: 30,
min: 15,
max: 100,
slide: function (event, ui) {
$("#portion").val(ui.value + " perc");
}
});
$("#portion").val($("#slider-range-min").slider("value") + " perc");
});
</script>
<script type="text/javascript">
$(function () {
$("#slider-range-min3").slider({
range: "min",
value: 500,
min: 100,
max: 10000,
slide: function (event, ui) {
$("#price").val(ui.value + " Ft");
}
});
$("#price").val($("#slider-range-min3").slider("value") + " Ft");
});
</script>
<script type="text/javascript">
$("<div>ASD</div>").appendTo("div#main");
</script>
<script type="text/javascript" language="javascript">
function DynamicDiv() {
var dynDiv = document.createElement("div");
dynDiv.id = "divDyna";
dynDiv.innerHTML = "Név:</label><div class=\"col-md-10\"><input class=\"form-control text-box single-line\" id=\"Preparation\" name=\"Preparation\" type=\"text\" value=\"\" /><span class=\"field-validation-valid text-danger\" data-valmsg-for=\"Preparation\" data-valmsg-replace=\"true\"></span></div></div>"
//dynDiv.innerHTML = "<div class=\"form-group\"><label class=\"control-label col-md-2\" for=\"Elk_sz_t_s\">Név</label><div class=\"col-md-10\"><input class=\"form-control text-box single-line\" id=\"Preparation\" name=\"Preparation\" type=\"text\" value=\"\" /><span class=\"field-validation-valid text-danger\" data-valmsg-for=\"Preparation\" data-valmsg-replace=\"true\"></span></div></div>"
//dynDiv.innerHTML = "<label>Név: <input type='text'>";
dynDiv.className = 'form-group control-label col-md-2';
document.getElementById("foo").appendChild(dynDiv);
}
</script>
}
Related
I want to retrieve data from textbox, when I but Id in the textbox it will retrieve rest of data in in other textbox here is my code:
controller:
[HttpPost]
public ActionResult Contact(int id)
{
testEntities db = new testEntities();
List<Table_1> tb = db.Table_1.ToList();
var c = tb.Find(m => m.id == id);
return View(c);
}
view
<div class="form-horizontal">
<h4>Table_1</h4>
<hr />
<form id="myForm">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.id, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.depart, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.depart, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.depart, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" value="Create" class="btn btn-default" id="btnSubmit">press here</button>
</div>
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#btnSubmit").click(function () {
debugger
var data = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "/Home/Contact",
data: data,
success: function (response) {
},
});
});
});
</script>
I use almost the same codes:
#model FormSubmitWebApplication.Models.Student
#{
ViewBag.Title = "Contact";
}
<div class="form-horizontal">
<h4>Table_1</h4>
<hr />
<form id="myForm">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Id, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" value="Create" class="btn btn-default" id="btnSubmit">press here</button>
</div>
</div>
</form>
</div>
#section scripts {
<script type="text/javascript">
$(document).ready(function () {
$("#btnSubmit").click(function () {
debugger
var data = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "/Home/Contact",
data: data,
success: function (response) {
},
});
});
});
</script>
}
The id could be passed to the controller.
Could you show the debug view in the controller?
I'm developing an administration page and I'm having trouble receiving my data from json.
I have a Create view and inside it I created a script to show my partial views when selecting a certain type. But when I select the Hotel type, my controller is not receiving the data. When I select the other types, it works well.
Can anyone tell me what the problem is?
My Code:
Create.cshtml
#model ProjetoFinal.Models.Item
#{
ViewBag.Title = "";
}
<h2>#Resource.Criar</h2>
Português |
Inglês
<br />
#using (Html.BeginForm("Create", "Trans", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="form-group">
#Html.LabelFor(model => model.Titulo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Titulo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Titulo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Descricao, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(model => model.Descricao, new { #class = "form-control", #id = "Descricao" })
#Html.ValidationMessageFor(model => model.Descricao, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Main_Image, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="col-md-10">
<input type="file" name="imagem_principal" id="createimageinput" />
#Html.ValidationMessageFor(model => model.Main_Image, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Localidade, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Localidade, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Localidade, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Endereco, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Endereco, new { htmlAttributes = new { #id = "Endereco", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Endereco, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Latitude, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Latitude, new { htmlAttributes = new { #id = "Latitude", #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.Latitude, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Longitude, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Longitude, new { htmlAttributes = new { #id = "Longitude", #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.Longitude, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Tipo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<!--Ao escolher o tipo vai aparecer os campos respetivos dessa categoria
atraves da funcao ddldropdown-->
#Html.DropDownListFor(model => model.Tipo, new SelectList(Model.tipos, "ID", "Tipo"), Resource.Selecionar_Tipo, htmlAttributes: new { #id = "ddldropdown", #class = "form-control" })
</div>
</div>
<div id="partialDiv">
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" id="btnsave" value="#Resource.Criar" class="btn btn-default" />
</div>
</div>
</div>
#section Scripts
{
<!--Script to add Views from the Others folder in the "partialDiv"-->
<script type="text/javascript">
$("#ddldropdown").change(function () {
var txt = $("#ddldropdown option:selected").text();
if (txt == null || txt == "Selecionar Tipo")
$('#partialDiv').html('');
else if (txt == "Teatro" || txt == "Feira" || txt == "Exposição" || txt == "Hotel" || txt == "Cinema" || txt == "Musica") {
$.ajax({
type: 'get',
url: '/Outros/Create_' + txt,
dataType: 'html',
success: function (html) {
$('#partialDiv').html(html);
}
});
}
else if (txt == "Parques/Percursos Pedestres") {
$.ajax({
type: 'get',
url: '/Outros/Create_Percurso',
dataType: 'html',
success: function (html) {
$('#partialDiv').html(html);
}
});
}
else {
$.ajax({
type: 'get',
url: '/Outros/Create_Other',
dataType: 'html',
success: function (html) {
$('#partialDiv').html(html);
}
});
}
});
</script>
<!--Script to submit partialDiv data-->
<script type="text/javascript">
window.jQuery(document).ready(function () {
$('#btnsave').click(function () {
var txt = $("#ddldropdown option:selected").text();
var frm = $("form");
var data = new FormData($("form")[0]);
if (txt == "Teatro" || txt == "Feira" || txt == "Exposição" || txt == "Hotel" || txt == "Cinema" || txt == "Musica") {
var files = $("#createimageinput").get(0).files;
// Add the uploaded file to the form data collection
if (files.length > 0) {
for (f = 0; f < files.length; f++) {
data.append("imgfile", files[f]);
}
}
$.ajax({
url: '/Outros/Create_' + txt,
method: "POST",
processData: false,
data: data,
dataType: 'html',
contentType: false,
});
}
else if (txt == "Parques/Percursos Pedestres")
{
$.ajax({
url: '/Outros/Create_Percurso',
method: "POST",
processData: false,
data: data,
dataType: 'html',
contentType: false,
});
}
else
{
if (txt != null || txt != "Selecionar Tipo")
{
$.ajax({
url: '/Outros/Create_Other',
method: "POST",
processData: false,
data: data,
dataType: 'html',
contentType: false,
});
}
}
});
});
</script>
<!--Script to place the Autocomplete at the Address-->
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCvSxmjQNuUVyhYFJ8SmXHa0sQKgpiLBLA&libraries=places">
function initMap() {
google.maps.event.addDomListener(window, 'load', function () {
var options = {
types: ['geocode'],
componentRestrictions: { country: "pt" }
};
var input = document.getElementById('Endereco');
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var near_place = autocomplete.getPlace();
document.getElementById('Latitude').value = near_place.geometry.location.lat();
document.getElementById('Longitude').value = near_place.geometry.location.lng();
});
});
}
$("#Endereco").change(function () {
document.getElementById('Latitude').value = '';
document.getElementById('Longitude').value = '';
});
</script>
<!--Google API-->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCvSxmjQNuUVyhYFJ8SmXHa0sQKgpiLBLA&libraries=places&callback=initMap"
async defer></script>
<script type="text/javascript">
$('#btnsave').click(function () {
var form = $("#formH");
var url = form.attr("action");
var formData = form.serialize();
$.post(url, formData, function (data) {
$("#msg").html(data);
});
})
</script>
}
<div>
#Html.ActionLink(Resource.Voltar, "Index")
</div>
}
Create_Hotel.cshtml
#model ProjetoFinal.Models.Hotel
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
#using (Html.BeginForm("Create_Hotel", "Outros", FormMethod.Post))
{
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Outras_Imagens, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="col-md-10">
<input type="file" name="images" multiple="multiple" id="imagens"/>
#Html.ValidationMessageFor(model => model.Outras_Imagens, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Preco, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Preco, new { htmlAttributes = new { #type = "number", #min = "0", #step = "0.01", #value = "0", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Preco, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Tipo_Hotel, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Tipo_Hotel, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Tipo_Hotel, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" id="div_comodidades">
#Html.LabelFor(model => model.Comodidades, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10" id="divCom">
<div class="input-group">
<span class="input-group-btn">
#Html.EditorFor(model => model.Comodidades, new { htmlAttributes = new { #id = "comodidades", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Comodidades, "", new { #class = "text-danger" })
<input type="button" class="btn btn-primary" id="com" value="+" onclick="addComodidades()" />
</span>
</div>
</div>
</div>
<div class="form-group" id="div_condicoes">
#Html.LabelFor(model => model.Condicoes, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10" id="divCon">
<div class="input-group">
<span class="input-group-btn">
#Html.EditorFor(model => model.Condicoes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Condicoes, "", new { #class = "text-danger" })
<input type="button" class="btn btn-primary" value="+" onclick="addCondicoes()" />
</span>
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Telefone1, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Telefone1, new { htmlAttributes = new { #type = "number", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Telefone1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Telefone2, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Telefone2, new { htmlAttributes = new { #type = "number", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Telefone2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Avaliacao, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Avaliacao, new { htmlAttributes = new { #type = "number", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Avaliacao, "", new { #class = "text-danger" })
</div>
</div>
</div>
#section Scripts
{
<script type="text/javascript">
var cont = 0;
var cont1 = 0;
//function to add more fields for the user to enter more comodidades
function addComodidades() {
cont++;
$("#div_comodidades").append(`<div class="col-md-10" id="campo` + cont + `" style="margin-left:16.7%">
<div class="input-group">
<span class="input-group-btn">
<input class="form-control text-box single-line" name="Comodidades" placeholder="Comodidades" type="text" value="" id="input_comodidades` + cont + `"/>
<span class="field-validation-valid text-danger" data-valmsg-for="Comodidades" data-valmsg-replace="true"></span>
<input type="button" id="` + cont + `" class="btn btn-primary" value="-" style="padding-left:15px;"/>
</span>
</div>
</div>`);
}
//function to add more fields for the user to enter more condicoes
function addCondicoes() {
cont1++;
$('#div_condicoes').append(`<div class="col-md-10" id="campo1` + cont1 + `" style="margin-left:16.7%">
<div class="input-group">
<span class="input-group-btn">
<input class="form-control text-box single-line" name="Condicoes" placeholder="Condicoes" type="text" value="" id="input_condicoes` + cont1 + `" />
<span class="field-validation-valid text-danger" data-valmsg-for="Condicoes" data-valmsg-replace="true"></span>
<input type="button" id="` + cont1 + `" class="btn btn-primary" value="-" style="padding-left:15px;"/>
</span>
</div>
</div>`);
}
//function to remove the comodidades field that the user added
$('#div_comodidades').on('click', '.btn-primary', function () {
var button_id = $(this).attr("id");
$('#campo' + button_id + '').remove();
});
//function to remove the condicoes field that the user added
$('#div_condicoes').on('click', '.btn-primary', function () {
var button_id = $(this).attr("id");
$('#campo1' + button_id + '').remove();
});
</script>
}
}
#{
Layout = null;
}
TransController.cs
public class TransController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(FormCollection formCollection)
{
Item item = new Item();
//add the database
}
}
OutrosController.cs
public class OutrosController : Controller
{
[HttpGet]
public ActionResult Create_Hotel()
{
Hotel hotel = new Hotel();
return View(hotel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create_Hotel(Hotel hotel, HttpPostedFileBase[] images)
{
//add the database
return View(hotel);
}
}
(Model) Hotel.cs
public class Hotel
{
public int ID { get; set; }
public String Preco { get; set; }
public String Comodidades { get; set; }
public List<String> array_comodidades { get; set; }
public String Condicoes { get; set; }
public List<String> array_condicoes{ get; set; }
[Display(Name = "Telefone")]
public int? Telefone1 { get; set; }
[Display(Name = "Telemovel/Fax")]
public int? Telefone2 { get; set; }
public String Email { get; set; }
public String Tipo_Hotel { get; set; }
[Range(0, 5)]
public String Avaliacao { get; set; }
public List<Imagem> Imagens { get; set; }
[Display(Name = "Imagens_Secundárias", ResourceType = typeof(Resource))]
public String Outras_Imagens { get; set; }
public class TransmontanosDBContext : DbContext
{
public DbSet<Hotel> Transmontanos { get; set; }
}
}
Problem:
Your ajax request specifies type, url, dataType and a callback success function but it never actually sends any of the form data with it (not sure why these fields are in a form any way if youre not using the form to submit the data to the server- but that's a different problem than your posting about.
To fix your issue, you should change your ajax request to a POST instead of GET and include your model data with it as follows:
var model = { Id = $("#Id").val(),
Preco = $("#Preco").val(),
//populate the rest of your fields here just like Id
};
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: '/Outros/Create_Percurso',
contentType: "application/json",
success: function (html) {
$('#partialDiv').html(html);
}
})
I have a view, in the view, I have a section where you can enter the customer account number and then press search
I want the search to query the SQLSERVER for the account number details and retrieve the other details like Name, Account Balance and the likes.
I have finished the View code but I am confused on how to implement the Controller and whether I should use AJAX to ensure that the page does not reload.
Could you advise me?
Below is the View.
#model CreditFacility_Web.Models.CreditFacilityModel.Transaction
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="w3-container" style="padding-left:60px">
#{
ViewBag.Title = "Credit Transaction";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h2>Credit Transaction</h2>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Account_Number, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Account_Number, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Account_Number, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button value="Search" class="btn btn-primary" >Search</button>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Firstname, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Firstname, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Firstname, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Surname, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Surname, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Surname, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Phone_Number, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Phone_Number, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Phone_Number, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Account_Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Account_Type, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Account_Type, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Old_Balance, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Old_Balance, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Old_Balance, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Amount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Amount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Amount, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.New_Balance, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.New_Balance, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.New_Balance, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Transaction_Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Transaction_Type, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Transaction_Type, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Narration, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Narration, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Narration, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-success" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
I have been able to work on the View and the Controller and below is what i have.
#section Scripts {
<script type="text/javascript">
$(document).ready(function () {
$(".btn-primary").click(function () {
var accNo = $('#Account_Number').val();
$.ajax({
url: "#Url.Action("AccountDetails", "Transactions")",
type: "POST",
dataType: "json",
data: { accountNo : accNo },
async: false,
error: function () {
alert('Account Number do not Exist Or Other Errors Occurred');
},
success: function (data) {
if (Object.keys(data).length > 0) {
$('#Firstname').val(data.Firstname);
$('#Old_Balance').val(data.Account_Balance);
}
}
});
});
});
</script>
}
And the Controller has the below.
[HttpPost]
public ActionResult AccountDetails(string accountNo)
{
using (var db = new CreditFacilityContext())
{
var accDetails = db.SavingsAccounts.Where(t => t.Account_Number == accountNo).Select(s => new SavingsAccount
{
Firstname = s.Firstname,
Account_Balance = s.Account_Balance,
//rest of properties
}).FirstOrDefault(); ;
return Json(accDetails, JsonRequestBehavior.AllowGet);
}
}
Ajax method to retrieve data without page refresh:
$(".btn-primary").click(function () {
var accNo = $('#Account_Number').val();
$.ajax({
url: "#Url.Action("AccountDetails", "Home")",
type: "POST",
dataType: "json",
data: { accountNo : accNo },
async: false,
error: function () {
},
success: function (data) {
if (Object.keys(data).length > 0) {
$('#Firstname').val(data.FirstName);
$('#Old_Balance').val(data.Balance);
}
}
});
});
Home Controller code to fetch data from SQL Server:
[HttpPost]
public JsonResult AccountDetails(string accountNo)
{
using (DBContextModel dataContext = new DBContextModel())
{
var accSearchParameter = new SqlParameter("#Search", accountNo);
var accDetails = dataContext.Database.SqlQuery<AccDetails>("EXEC YourStoredProc #Search", accSearchParameter ).Select(s => new AccDetails
{
FirstName = s.FirstName,
Balance = s.Balance,
//rest of properties
}).SingleOrDefault();
return Json(accDetails, JsonRequestBehavior.AllowGet);
}
}
Pre-requisites for the Controller code to work:
Stored procedure
AccDetails class with properties that match the select column names/aliases of SP. Try this, I think you probably need to read up on jQuery Ajax and JSON in MVC.
I have a form for adding Books in a database,
I Have a modal window in my form to create a Publisher, if the specified format doesn't exist in Publisher Dropdown, I Create my Modal in a partial view for add Publisher,
this is my view:
#model WebApplication3.Models.BookModel
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div id="CustomerList"></div>
<h2>Create New Book</h2>
<label class="text-#ViewBag.ClassName">
#ViewBag.Message
</label>
#using (Html.BeginForm("CreateBook", "Book", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.TitleID, "TitleID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("TitleID", null, "Select a Title", htmlAttributes: new { #class = "form-control" })
#Html.ActionLink("Add New", "Create", "Title")
#Html.ValidationMessageFor(model => model.TitleID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FormatID, "FormatID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("FormatID", null, "Select a Format", htmlAttributes: new { #class = "form-control" })
<a href="" class="" data-toggle="modal" data-target="#FormatModal">
Add New
</a>
#Html.ValidationMessageFor(model => model.FormatID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ISBN, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ISBN, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ISBN, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Quantity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Quantity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</div>
</div>
}
<div class="modal fade" id="PublisherModal" tabindex="-1" role="dialog" aria-labelledby="publisherModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
#Html.Partial("_Publisher")
</div>
</div>
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryajax")
}
and this is my Publisher partial view:
#model WebApplication3.Models.PublisherModel
#using (Ajax.BeginForm("CreatePublisher", "Book", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "publisherForm", InsertionMode = InsertionMode.ReplaceWith }))
{
<div id="publisherForm">
<div class="modal-header">
<h5 class="modal-title" id="publisherModalLongTitle">Create New Publisher</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
<span class="text-#ViewBag.ClassName">
#ViewBag.Message
</span>
</div>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Value, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Value, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Value, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
#Html.ActionLink("Manage", "Index", "Publisher", new { area = "" }, new { #class = "btn btn-link" })
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</div>
}
and this is my controller
[HttpPost]
[ValidateAntiForgeryToken]
public PartialViewResult CreatePublisher([Bind(Include = "ID,Value,Description")] PublisherModel publisherModel)
{
ViewBag.TitleID = new SelectList(repoTitle.GetModels(), "ID", "Title");
ViewBag.FormatID = new SelectList(repoFormat.GetModels(), "ID", "Value");
PublisherModel publisher = repoPublisher.GetModels().FirstOrDefault(x => x.Value == publisherModel.Value);
if (publisher == null)
{
if (ModelState.IsValid)
{
repoPublisher.Insert(publisherModel);
ViewBag.PublisherID = new SelectList(repoPublisher.GetModels(), "ID", "Value", publisherModel.ID);
ViewBag.Message = $"Publisher \"{publisherModel.Value}\" Added Successfully";
ViewBag.ClassName = "success";
return PartialView("_Publisher");
}
}
else
{
ViewBag.Message = $"Publisher \"{publisherModel.Value}\" Already Exsisted";
ViewBag.ClassName = "danger";
}
ViewBag.PublisherID = new SelectList(repoPublisher.GetModels(), "ID", "Value");
return PartialView("_Publisher",publisherModel);
}
How Can change to my code that if a new Publisher inserted to Database, the Publisher dropdown refresh and select newly inserted data as a selected item?
About question
I can't run your code locally.
These operations can be implemented through JS.
I can show my tools.
This is the function gif:
Solution:
Select and add options as a whole.
// index.cshtml
<div>
#await Component.InvokeAsync("AutoAddListValue")
</div>
//Component
#model List<string>
<h3>Default page</h3>
<div>
<div>
<p>Lists</p>
<select name="select" class="" id="ComponentSelectId" onclick="ComponentSelectClick()">
<option id="ComponentOptionId" style="width:auto">ComponentTest</option>
#if (Model.Count != 0)
{
int count = Model.Count();
for (int item = 0; item < count; item++)
{
<option id="option">#Model[item].ToString()</option>
}
}
</select>
</div>
<div>
<input id="ComponentTestJsInput" class="d-none" value="132323" type="text" />
<input id="ComponentBtnDisplay" value="Add" type="button" class="btn btn-primary" onclick="ComponentBtnDisplayClick()">
<input id="ComponentBtnAdd" value="Add" type="button" class="btn btn-primary d-none" onclick="ComponentBtnAddClick()">
</div>
</div>
Bind data for components.
public class AutoAddListValueViewComponent : ViewComponent
{
private readonly SchoolContext _context;
public AutoAddListValueViewComponent(SchoolContext context)
{
_context = context;
}
public async Task<IViewComponentResult> InvokeAsync(
int maxPriority, bool isDone)
{
string MyView = "Default";
var items = await GetListAsync();
return View(MyView, items);
}
public async Task<List<string>> GetListAsync()
{
return await _context.Test.Select(o => o.Name).ToListAsync();
}
}
Using JS code to realize page interaction.
var ComponentBtnDisplayClick = function () {
$('#ComponentBtnAdd').removeClass("d-none");
$('#ComponentTestJsInput').removeClass("d-none");
$('#ComponentBtnDisplay').addClass("d-none");
}
var ComponentBtnAddClick = function () {
//alert("666666");
$('#ComponentBtnAdd').addClass("d-none");
$('#ComponentTestJsInput').addClass("d-none");
$('#ComponentBtnDisplay').removeClass("d-none");
inputVal = $('#ComponentTestJsInput').val();
//alert(inputVal);
$.ajax({
url: '/Test/SaveInputValue',
data: {
name: inputVal
},
type: 'post',
async: true,
cache: false,
success: function (data) {
//alert(data.code);
var option = "<option id='ComponentOptionId'>";
option += inputVal;
option += "</option>";
$("#ComponentSelectId").append(option);
var obj = document.getElementById("ComponentSelectId");
obj[obj.length - 1].selected = true;
},
error: function () {
alert('fail');
}
});
}
Other code
Source Code
I want to export my Viewmodel from my view to my controller which is receiving it in a method, this is my view:
#using Resources
#model MyProject.ViewModel.CertificationViewModel
#{
ViewBag.Title = Resources.titleCertificationList;
#section css
{
<link href="#Url.Content("~/layout/css/stylesformador.css")" rel="stylesheet" />
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
}
}
<div class="mainblock">
<div class="block-group">
<div class="ttitle title">#HIQResources.titleEdit</div>
</div>
#using (Html.BeginForm("Edit", "Certification", FormMethod.Post, new { id = "form1" }))
{
#Html.AntiForgeryToken()
<div class="md-content">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.pdf, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#*<input type="file" name="file" />*#
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control inputForm", #type="file" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Code, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Code, new { htmlAttributes = new { #class = "form-control inputForm", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.Code, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SelectedEntityId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.DropDownListFor(model => model.SelectedEntityId, Model.EntitiesDrop, htmlAttributes: new { #class = "form-control inputForm" })
#Html.HiddenFor(model => model.SelectedEntityId)
#Html.ValidationMessageFor(model => model.SelectedEntityId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StatusId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.DropDownListFor(model => model.StatusId, Model.StatusDrop, htmlAttributes: new { #class = "form-control inputForm" })
#Html.HiddenFor(model => model.StatusId)
#Html.ValidationMessageFor(model => model.StatusId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Result, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Result, new { htmlAttributes = new { #class = "form-control inputForm" } })
#Html.ValidationMessageFor(model => model.Result, "", new { #class = "text-danger"})
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Date, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control inputForm" } })
#Html.ValidationMessageFor(model => model.Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Observation, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Observation, new { htmlAttributes = new { #class = "form-control inputForm" } })
#Html.ValidationMessageFor(model => model.Observation, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-1">
<div class="col-md-8">
<table class="table table-bordered">
<tr>
<th class="col-md-2">
#Html.DisplayNameFor(model => model.FileName)
</th>
<th class="col-md-2">Ficheiro</th>
</tr>
#foreach (var item in Model.teste)
{
<tr>
<td>
#if (item.FileName == null)
{
<h5>Não existem ficheiros para esta certificação.</h5>
}
else
{
#Html.DisplayFor(modelItem => item.FileName)
}
</td>
<td>
#if (item.FileName == null)
{
<h5>Não existem ficheiros para esta certificação.</h5>
}
else
{
Download
#*Delete*#
<input type="submit" value="Edit" id="Delete" class="btn btn-default btn-sm btn-detail" />
}
#*#Html.ActionLink("Download", "Certification", "Download", new { id = Model.Id })*#
</td>
</tr>
}
</table>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-8">
<input type="submit" value="#HIQResources.buttonSave" class="btn btn-default btn-sm btn-detail" />
#Html.ActionLink(HIQResources.buttonBack, "CertificationList", new { id = Model.StudentId, nome = Model.StudentName }, new { #class = "btn btn-default btn-sm btn-edit" })
</div>
</div>
</div>
</div>
}
</div>
#section Scripts {
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/HIQTrainingScripts/Certification/Edit.js"></script>
<script>
$("#Date").datepicker({ dateFormat: 'yy/mm/dd' });
$("#Delete").click(function () {
var vm = $('#Model').serialize();
alert(vm)
var token = $('input[name="__RequestVerificationToken"]').val();
$.ajax({
url: "/Certification/Edit",
type: "POST",
data: {
__RequestVerificationToken: token,
vm: vm,
click: "deu",
},
sucess: function (result) {
alert("sucess");
}
});
});
</script>
}
This is the method in my controller:
[Authorize(Roles = "Admin, Staff")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(CertificationViewModel vm, string click) {
if (click == "deu")
{
int lol = _servicesFactory.GetService<ICertificationManager>().DeleteFile(vm, GetLoggedUser());
return View(vm);
}
}
The value of my ViewModel comes always as null to my Jquery variable and I don't know why, because it should come with the info from the view to the controller in order for me, to execute my task.
Am I missing something ?