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);
}
})
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 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 am new to mvc and am trying to do something like in the below image (im not using partial views).
I have an IEnumerable property on Model
Like in this image, (i have not enough reputation to show image directly)
but on controller if i put FormCollection as parameter to accepting post method when i process same name fields i get an extra character ',', which might be also used by user...
Any idea....
[EDIT]
My view
#model Models.Question
#{
ViewBag.Title = "Add";
}
<h2>Add</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Question</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.SurveyId)
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.QuestionTypeId, "Question type", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.QuestionTypeId, new SelectList(ViewBag.QuestionTypes, "QuestionTypeId", "Name"), new { #class = "form-control col-md-10" })
<button type="button" class="btn btn-default addAnswer hide"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span></button>
#Html.ValidationMessageFor(model => model.QuestionTypeId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group hide">
#Html.LabelFor(model => model.Answers, "Options", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10" id="allAnswers">
#Html.ValidationMessageFor(model => model.Answers, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Sort, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Sort, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Sort, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Mandatory, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Mandatory)
#Html.ValidationMessageFor(model => model.Mandatory, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Question", "Survey", new { id = Model.SurveyId }, null)
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval", "~/Scripts/QuestionAdd.js")
}
Controller
[HttpGet]
public ActionResult Add(long id)
{
var question = new Models.Question();
question.SurveyId = id;
ViewBag.QuestionTypes = BLL.Questions.GetQuestionTypes();
return View(question);
}
[HttpPost]
public ActionResult Add(FormCollection coll)
{
if (ModelState.IsValid)
{
var question = new Models.Question();
question.Name = coll["Name"];
byte qid = 0, sort = 0;
bool mandatory = false;
byte.TryParse(coll["QuestionTypeId"], out qid);
byte.TryParse(coll["Sort"], out sort);
bool.TryParse(coll["Mandatory"], out mandatory);
question.QuestionTypeId = qid;
question.Sort = sort;
question.Mandatory = mandatory;
foreach (var answer in coll["Answers"])
question.Answers.Add(new Models.Answer() { Value = answer + "" });
if (question != null)
{
if (BLL.Questions.Insert(question) != null)
ViewBag.Message = "Successfully inserted";
else
ViewBag.Message = "Insert could not be done";
return RedirectToAction("Index", "Question", new { questionId = question.QuestionId });
}
}
return View();
}
When (+) clicked
$('#allAnswers').append(
'<div class="input-group col-lg-4">' +
'<input class="form-control" name="Answers"> ' +
'<div class="input-group-btn">' +
' <button type="button" class="btn btn-default removeAnswer"><span class="glyphicon glyphicon glyphicon-trash" aria-hidden="true"></span></button>' +
'</div> </div>');
As discussed.. here is how i would approach this.
I have a view model to hold the questions and answers and the selected question to which we will be adding answers.
public class CurrentViewModel
{
public string QuestionSelected { get; set; }
public List<SelectListItem> Questions { get; set; }
public List<string> Answers { get; set; }
}
Then in your controller we have an action to return the view, an action to get the answers for the selected question, an action to add a new answer for the selected question and also a save method which just demonstrates the final model content posted.
public class TestController : Controller
{
public ActionResult Test()
{
var model = new CurrentViewModel()
{
Questions = new List<SelectListItem>()
{
new SelectListItem()
{
Text = "Question 1",
Value = "Question 1"
},
new SelectListItem()
{
Text = "Question 2",
Value = "Question 2"
}
},
Answers = new List<string>()
};
return View("Test", model);
}
public PartialViewResult GetAnswers(CurrentViewModel model)
{
model.Answers = new List<string>();
//model.Answers = Get Answers from some service based on QuestionSelected?!
model.Answers.Add("Answer 1");
model.Answers.Add("Answer 2"); //Add manuall for example
return PartialView("_Answers", model);
}
public PartialViewResult AddAnswer(CurrentViewModel model)
{
model.Answers.Add("Add answer here...");
return PartialView("_Answers", model);
}
public ActionResult SaveQuestionsAndAnswers(CurrentViewModel model)
{
if (model.Questions.Count == 0)
{
}
return View("Test", model);
}
}
Then we have a main view for showing the questions dropdown and a partial view that will show us the answers.
Main View
#model TestMVC.Models.CurrentViewModel
#{
ViewBag.Title = "Test";
}
<link href="~/Content/StyleSheets/jquery-ui.css" rel="stylesheet" />
<script src="~/Content/Scripts/jquery-2.2.3.js"></script>
<script src="~/Content/Scripts/jquery-ui-1.11.4.js"></script>
<div id="divBodyContent">
<div>
<h3>Q & A</h3>
</div>
#using (Html.BeginForm("SaveQuestionsAndAnswers", "Test", FormMethod.Post, new { id = "frmQandA" }))
{
#Html.Label("lblQ", "Questions", new { #class = "form-control inline" })
#Html.DropDownListFor(model => model.QuestionSelected, Model.Questions, "Select--", new { #class = "form-control inline", id="ddQuestions" })
<div id="divAnswers">
#Html.Partial("_Answers")
</div>
<div style="margin-top: 1%;">
<button id="btnSave" type="submit" class="btn btn-primary" style="margin-left: 4px; margin-bottom: 10px; width: 7%">save</button>
</div>
}
</div>
<script>
$("#ddQuestions").on("change", function() {
var myData = $('#frmQandA').serialize();
$.ajax({
type: "POST",
url: "#Url.Action("GetAnswers", "Test")",
data: myData,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function(data) {
$("#divAnswers").html(data);
}
})});
</script>
Partial View
#model TestMVC.Models.CurrentViewModel
<link href="~/Content/StyleSheets/jquery-ui.css" rel="stylesheet" />
<script src="~/Content/Scripts/jquery-2.2.3.js"></script>
<script src="~/Content/Scripts/jquery-ui-1.11.4.js"></script>
<div>
#for (var counter = 0; counter <= (Model.Answers.Count - 1); counter++)
{
#Html.TextBoxFor(model => model.Answers[counter], new {#class = "form-control inline"})
}
<div style="margin-top: 1%;">
<button id="btnAddAnswer" type="button" class="btn btn-primary" style="margin-left: 4px; margin-bottom: 10px; width: 7%">Add</button>
</div>
</div>
<script>
$("#btnAddAnswer").on("click", function() {
var myData = $('#frmQandA').serialize();
$.ajax({
type: "POST",
url: "#Url.Action("AddAnswer", "Test")",
data: myData,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function (data) {
$("#divAnswers").html(data);
}
})});
</script>
I've tested this locally and it works. In a nutshell, when we need a new answer adding to the model, we add it in server side so we can then bind to the model in the browser. We do this via an Ajax call on the change event of the questions drop down. The partial view iterates through each answer via a counter which generates a unique id and textbox for each answer. Adding a new answer is also achieved via ajax. These can then all be posted back.
Hope that helps.
I would want to insert multiple entries in my table called 'sibling' using it's Create Method (which I generated automatically using Scaffolding methods). I already made the form dynamic in adding the fields. However, when I click on the Submit button it only gets the first entry.
I sort of have an idea by implementing 'foreach' in the said method but I can't seem to find an answer that is spot on. Especially for my case I just want to modify the Create Method for 'sibling' which was generated automatically (if there is such a way without having to create a new method - but if not I am fine with a different approach as well).
This is my SiblingController:
public ActionResult Create(int id)
{
var sib = new sibling();
sib.child_id = id;
return View(sib);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "sibling_id,child_id,age,gender")] sibling sibling)
{
if (ModelState.IsValid)
{
db.siblings.Add(sibling);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.child_id = new SelectList(db.children, "child_id", "last_name", sibling.child_id);
return View(sibling);
}
This is my Create.cshtml for Sibling:
#model dummyApp.Schema.TestModels.sibling
#{
ViewBag.Title = "Create";
}
#section Scripts{
<script type="text/javascript">
//Coding
$("#numBox").change(function () {
var htmlString = "";
var len = $(this).val();
for (var i = 0; i < len; i++) {
htmlString += ' <div class="form-group">\
#Html.LabelFor(model => model.child_id, "child_id", htmlAttributes: new { #class = "control-label col-md-2" })\
<div class="col-md-10">\
#Html.EditorFor(model => model.child_id, new { htmlAttributes = new { #class = "form-control" }})\
#Html.ValidationMessageFor(model => model.child_id, "", new { #class = "text-danger" })\
</div>\
</div>\
<div class="form-group">\
#Html.LabelFor(model => model.age, htmlAttributes: new { #class = "control-label col-md-2" })\
<div class="col-md-10">\
#Html.EditorFor(model => model.age, new { htmlAttributes = new { #class = "form-control" } })\
#Html.ValidationMessageFor(model => model.age, "", new { #class = "text-danger" })\
</div>\
</div>\
<div class="form-group">\
#Html.LabelFor(model => model.gender, htmlAttributes: new { #class = "control-label col-md-2" })\
<div class="col-md-10">\
#Html.EditorFor(model => model.gender, new { htmlAttributes = new { #class = "form-control" } })\
#Html.ValidationMessageFor(model => model.gender, "", new { #class = "text-danger" })\
</div>\
</div>\
';
}
$("#adtnl_fields").html(htmlString);
})
</script>
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>sibling</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<!--
<div class="form-group">
#Html.LabelFor(model => model.sibling_id, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.sibling_id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.sibling_id, "", new { #class = "text-danger" })
</div>
</div>
-->
<div class="form-group">
#Html.Label("Number of Siblings:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="number" id="numBox" class="form-control"/>
</div>
</div>
<!--
<div class="form-group">
#Html.LabelFor(model => model.child_id, "child_id", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*Html.DropDownList("child_id", null, htmlAttributes: new { #class = "form-control" })*#
#Html.EditorFor(model => model.child_id, new { htmlAttributes = new { #class = "form-control" }})
#Html.ValidationMessageFor(model => model.child_id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.age, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.age, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.age, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.gender, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.gender, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.gender, "", new { #class = "text-danger" })
</div>
</div>
-->
<!-- Div for additional fields -->
<div id="adtnl_fields">
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
This is my 'sibling.cs':
public partial class sibling
{
public int sibling_id { get; set; }
public int child_id { get; set; }
public Nullable<int> age { get; set; }
public string gender { get; set; }
public virtual child child { get; set; }
}
Please help. Thank you!
You can use AddRange method in EF-6
IList<Student> newStudents = new List<Student>();
newStudents.Add(new Student() { StudentName = "Student1 by addrange" });
newStudents.Add(new Student() { StudentName = "Student2 by addrange" });
newStudents.Add(new Student() { StudentName = "Student3 by addrange" });
using (var context = new SchoolDBEntities())
{
context.Students.AddRange(newStudents);
context.SaveChanges();
}
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>
}