I have a view with a model that post data to controller but after submitting, posted model has default values. How can I resolve this issue?
My Model:
public partial class SaleModel
{
[Required]
public byte CategoryId { get; set; }
[Required]
public int UserId { get; set; }
[Required]
[Range(1, int.MaxValue)]
public int ProductId { get; set; }
[Required]
[StringLength(11)]
[RegularExpression("^(989|09|9)[012349][0-9]\\d{7}$")]
public string Mobile { get; set; }
[Required]
[Range(5000, 10000000]
public int Amount { get; set; }
[Required]
public float DiscountPercent { get; set; }
}
I have to submit button in view and string submit in Controller for that:
#using EKhadamat.Models.Sales
#using EKhadamat.Services.Operators
#using EKhadamat.Core.Models.Products
#model SaleModel
#inject IOperatorService operatorService
#{
ViewData["Title"] = "شارژ ارزان";
var category = Category.Charge;
}
#using (Html.BeginForm("Sale", "Topup", FormMethod.Post))
{
<div class="card border border-primary shadow view-height bg-light">
<div class="card-body">
<div class="row">
<div class="col-lg-6">
<h1 class="text-primary">
شارژ ارزان
<label id="lblDescription"></label>
</h1>
<h6 class="text-info mb-3"><span class="fas fa-hand-point-left fa-fw ml-1"></span>با 2 درصد تخفیف، سیم کارت اعتباری خود را شارژ کنید.</h6>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fas fa-mobile-alt fa-fw text-primary"></i>
</span>
</div>
<input asp-for="Mobile" class="form-control" type="number" placeholder="#Html.DisplayFor(model => model.Mobile)" />
<button ID="LNK_Charge_Contacts" class="btn btn-info" title="لیست مخاطبین" CommandArgument="TB_Charge_Mobile">
<span class="fas fa-address-book fa-fw fa-inverse"></span>
</button>
</div>
<div class="mb-2">
<span asp-validation-for="Mobile" class="text-danger text-desc"></span>
</div>
...
<button id="btnSubmit" type="button" class="btn btn-block btn-primary mb-5">بررسی نهایی</button>
<div id="divReceipt" class="d-none">
<div class="row">
<div class="col-12">
<div class="alert alert-success mb-2" role="alert">
<h4>
<span>پیشفاکتور</span>
<span class="fas fa-receipt fa-fw float-left"></span>
</h4>
<hr />
<label id="lblTitle"></label>
<br />
<label id="lblOperator"></label>
<br />
<label id="lblMobile"></label>
<br />
<label id="lblCount"></label>
<hr />
<div class="text-center">
<span class="fas fa-2x fa-coins fa-fw ml-1 text-gold"></span>
<label id="lblPayment"></label>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6 col-sm-6">
<button id="btnCredit" type="submit" name="submit" value="Credit" class="btn btn-block btn-info mb-2" disabled="#Model.UserId <= 0 ? 'disabled' : ''">خرید اعتباری</button>
</div>
<div class="col-lg-6 col-sm-6">
<button id="btnCash" type="submit" name="submit" value="Cash" class="btn btn-block btn-primary mb-2">خرید نقدی</button>
</div>
</div>
<button id="btnReturn" type="button" class="btn btn-block btn-secondary mb-5">بازگشت و ویرایش</button>
</div>
</div>
<div class="col-lg-6">
<div class="card">
<div class="card-body">
<img id="imgCharge" src="~/img/charge.jpg" class="img-fluid" alt="شارژ ارزان ایرانسل، شارژ ارزان همراه اول و شارژ ارزان رایتل" />
<div class="ribbon animated infinite pulse">
<span>2 درصد تخفیف</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
#section Scripts {
<partial name="_ValidationScriptsPartial" />
<script>
$("#rblOperators").change(function () {
var checkedRadio = $("#rblOperators input:checked");
var operatorId = checkedRadio.val();
var ddl = $("##Html.IdFor(model => model.ProductId)");
$.ajax({
cache: false,
url: "#(Url.Action("GetTopupListByOperator", "Topup"))",
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
"operatorId": operatorId
},
success: function (data, textStatus, jqXHR) {
ddl.html('');
$.each(data, function (i, option) {
ddl.append($("<option></option>").val(option.id).html(option.name).data("desc", option.desc));
});
}
})
});
--jquery code for show/hide elements or get data from controller
</script>
}
My controller action:
[HttpPost]
public virtual IActionResult Sale(SaleModel saleModel, string submit)
{
switch (submit)
{
case "Cash":
break;
case "Credit":
break;
}
return View();
}
for example after submitting form, productid=0 and mobile is empty.
I have a button before submit buttons and on click form validation occurred and model was being cleaned. I changed button type to submit and used form validation in controller.
Related
I am working on my college website project we created APIs for store data and retrieve data from the Database. Now I am integrating this API in to the admin panel but I don't know how to create a POST method or NewsAdd method.
This is my controller code.
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using BACKEND_HTML_DOT_NET.Models;
using Newtonsoft.Json;
using System.Text;
using RestSharp;
namespace BACKEND_HTML_DOT_NET.Controllers
{
public class News : Controller
{
private string apiBaseUrl = "https://localhost:44374/api";
HttpClient hc = new HttpClient();
private List<NewsVM> newsVMList = new List<NewsVM>();
public IActionResult NewsList()
{
var restClient = new RestClient(apiBaseUrl);
var restRequest = new RestRequest("/GetAllNewsDetails", Method.Get);
restRequest.AddHeader("Accept", "application/json");
restRequest.RequestFormat = DataFormat.Json;
RestResponse response = restClient.Execute(restRequest);
var content = response.Content;
var user = JsonConvert.DeserializeObject<ServiceResponse<List<NewsVM>>>(content);
newsVMList = user.data;
return View(newsVMList);
}
public IActionResult NewsView(int id=0)
{
NewsVM newsVM = new NewsVM();
newsVM = newsVMList.Where(m => m.Id == id).FirstOrDefault();
return View(newsVM);
}
public IActionResult NewsAdd()
{
return View();
}
}
}
This is my cshtml page
#model List<BACKEND_HTML_DOT_NET.Models.NewsVM>
#{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "NewsAdd";
}
<div class="content-wrapper">
<!-- <h3 style="margin-left: 15px;">DEPARTMENT</h3> -->
<section class="content" style="margin-top:20px;">
<div class="row">
<div class="col-md-12">
<a href="#Url.Action("NewsList","News")">
<ol class="breadcrumb float-sm-right">
<li style="margin-left: 00px;"><i class="nav-icon fas fa-minus-circle"></i></li>
<li style="margin-left: 00px;">Back to Details</li>
</ol>
</a>
</div>
<div class="col-md-12">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">Add New News</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form id="newsaddform" asp-action="NewsAdd" asp-controller="News" method="post" role="form">
#using(Html.BeginForm()){
<div class="card-body">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="exampleInputText">ENTER TITLE OF NEWS</label>
<input type="text" name="title" class="form-control" id="exampleInputEmail1" placeholder="ENTER TITLE.. ">
</div>
</div>
<div class="col-md-6">
<label for="description">ENTER DESCRIPTION OF NEWS</label>
<textarea type="text" name="description" class="form-control" id="description" rows="4" placeholder="Write content"></textarea>
</div>
</div>
</div>
<div class="card-footer">
<div class="input-group col-12">
<div class="col-sm-6"><button type="submit" id="sub" class="btn btn-primary float-right col-md-2">Submit</button></div>
<div class="col-sm-6"><button type="reset" class="btn btn-default col-md-2">Clear</button></div>
</div>
</div>
}
</form>
</div>
</div>
<!-- /.card-body -->
</div>
</section>
</div>
#section script{
<script type="text/javascript">
$(document).ready(function() {
//console.log( "ready!" );
$('#newsaddform').validate({
rules: {
"title": {
required: true
},
"description": {
required: true
}
},
messages: {
"title": {
required: "this field is required"
},
"description": {
required: "this field is required"
}
}
});
$('#newsaddform').submit(function(e) {
//prevent Default functionality
e.preventDefault();
if($('#newsaddform').valid()){
var dataForm = new FormData($('#newsaddform')[0]);
$.ajax({
url: '#Url.Action("NewsAdd","News")',
type: 'post',
crossDomain: true,
enctype: 'multipart/form-data',
dataType: 'application/json',
processData: false,
contentType: false,
data: dataForm,
success: function(data) {
console.log(data);
}
});
}
});
});
</script>
}
This is the model class
using System;
using System.Collections.Generic;
namespace BACKEND_HTML_DOT_NET.Models
{
public class NewsVM
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime Date { get; set; }
public bool? IsDeleted { get; set; }
public DateTime? CreatedDate { get; set; }
public string CreatedDateInt { get; set; }
public DateTime? UpdatedDate { get; set; }
public string UpdatedDateInt { get; set; }
}
}
When you select form submit(method="post"),you can send the post request directly by clicking the Submit button(type="submit"), this will submit the content of your input box by default,and don't need to send the post request through Ajax.
Below is my test code,you can refer to it:
View:
#model _2022072601.Models.NewsVM
<div class="content-wrapper">
<!-- <h3 style="margin-left: 15px;">DEPARTMENT</h3> -->
<section class="content" style="margin-top:20px;">
<div class="row">
<div class="col-md-12">
<a href="#Url.Action("NewsList","News")">
<ol class="breadcrumb float-sm-right">
<li style="margin-left: 00px;"><i class="nav-icon fas fa-minus-circle"></i></li>
<li style="margin-left: 00px;">Back to Details</li>
</ol>
</a>
</div>
<div class="col-md-12">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">Add New News</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form id="newsaddform" asp-action="NewsAdd" asp-controller="Home" method="post" role="form">
#using(Html.BeginForm()){
<div class="card-body">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="exampleInputText">ENTER TITLE OF NEWS</label>
<input type="text" name="title" class="form-control" id="exampleInputEmail1" placeholder="ENTER TITLE.. ">
</div>
</div>
<div class="col-md-6">
<label for="description">ENTER DESCRIPTION OF NEWS</label>
<textarea type="text" name="description" class="form-control" id="description" rows="4" placeholder="Write content"></textarea>
</div>
</div>
</div>
<div class="card-footer">
<div class="input-group col-12">
<div class="col-sm-6"><button type="submit" id="sub" class="btn btn-primary float-right col-md-2">Submit</button></div>
<div class="col-sm-6"><button type="reset" class="btn btn-default col-md-2">Clear</button></div>
</div>
</div>
}
</form>
</div>
</div>
<!-- /.card-body -->
</div>
</section>
</div>
Controller:
[HttpGet]
public IActionResult NewsAdd()
{
return View();
}
[HttpPost]
public JsonResult NewsAdd(NewsVM newsVM)
{
return Json(newsVM);
}
Test Result:
For more details, please refer to this link.
So adjournHearingInfo's newHearingDate when I do not fill it in as the error message of
The value '' is invalid." with a value of "1/1/0001 12:00:00 AM"
I cannot figure out how to access this check its doing to change this error message. Or if that is not possible remove this check so I can validate the date myself and then generate the error message I want. Is this possible?
Currently I am able to add another error message to it, but I cannot remove that one.
DTO:
public class AdjournHearingDTO
{
public int HearingID { get; set; }
[Required(ErrorMessage ="Please enter a Date")]
[Display(Name ="Additional Hearing Date")]
[Range(typeof(DateTime), "1/1/1900","1/1/2060", ErrorMessage =("Please enter a valid date."))]
public DateTime newHearingDate { get; set; }
}
Cshtml:
public AdjournHearingDTO adjournHearingInfo { get; set; }
public IActionResult OnPost()
{
if (ModelState.IsValid)
{
}
else
{
if (adjournHearingInfo.newHearingDate.Date.ToString() == "1/1/0001 12:00:00 AM")
{
ModelState.AddModelError("adjournHearingInfo.newHearingDate", "Invalid Date");
};
return Page();
}
}
HTML:
<form asp-page="AdjournHearing" method="post" name="AdjournHearingScreen" id="AdjournHearingForm">
#if (!Model.ModelState.IsValid)
{
<div class="row">
<div class="col-md-offset-2 col-md-10">
<h3 class="text-danger">Validation Errors</h3>
#*#Html.ValidationSummary(true, "", new { #class = "text-danger"})*#
<div asp-validation-summary="All"></div>
</div>
</div>
}
<div class="container">
<h1 class="mt-4 mb-3">
<button asp-page-handler="Back" class="btn btn-secondary">Back</button>
</h1>
<div class="row">
<div>
<h4>Case: #Model.HearingDetail.CaseName</h4>
<h5>
Hearing: #Model.HearingDetail.Name
</h5>
<div class="row">
<div class="card RoundedCorners">
<h6>Hearing Date: #Model.NewestHearingDate.ToString("g")</h6>
<div class="form-group">
<label asp-for="adjournHearingInfo.newHearingDate" class="control-label"></label>
<input asp-for="adjournHearingInfo.newHearingDate" class="form-control" />
<span asp-validation-for="adjournHearingInfo.newHearingDate" class="text-danger"></span>
</div>
<div class="" style="padding:1em 0 0 0;">
<button id="SubmitButton" class="btn btn-primary" type="submit"> Submit </button>
<button id="SubmitButtonDisabled" disabled style="display:none" class="btn btn-primary" type="submit"> Submit </button>
</div>
</div>
</div>
</div>
</div>
</div>
<input asp-for="HearingDetail.HearingID" type="hidden" />
</form>
Go to wwwroot\lib\jquery-validation\dist\additional-methods.js and find
$.validator.messages.date );
Try to delete either just the message or the whole line and see if it works.
I have an application which simulates a clothing site.I try to build my C# object with the data that the user writes in the form and the products they bought on the site.The products are represented by a JSON object.I use 2 classes: one for the shopping cart and one for the product.
public class Product
{
[Key]
public int id { get; set; }
public string productName { get; set; }
public string productPrice { get; set; }
public string quantity { get; set; }
}
public class ShoppingCart
{
[Key]
public int? id { get; set; }
public List<Product> productList { get; set; }
public string clientName { get; set; }
public string clientAddress { get; set; }
public string clientMail { get; set; }
}
I use a controller which has the method "Save" which uses the [FromForm] attribute.After the objects is binded from the client side I add it to my database.The problem is that I get "null" values for every property in my ShoppingCart object that is sent to the method.Moreover in my browser, the data is sent correctly to the server:
screenshot from network tab in chrome
The controller that I use looks like this:
[Route("SendItems/Save")]
[ApiController]
public class SendItemsController : Controller
{
private AppDbContext _db;
public SendItemsController(AppDbContext db)
{
_db = db;
}
[HttpPost]
[Consumes("application/json")]
public async Task<IActionResult> Save([FromForm] ShoppingCart s)
{
await _db.ShoppingCarts.AddAsync(s);
await _db.SaveChangesAsync();
return RedirectToAction("Index");
}
[HttpGet("~/ThankYou/Index")]
public IActionResult Index()
{
return View();
}
}
My html for the form is written like this:
#model ShoppingCart
<div class="form-group row">
<div class="col-4">
<label id="clienId"></label>
</div>
<div class="col-6">
<input asp-for="id" id="idClient" type="hidden" />
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label id="clientProds"></label>
</div>
<div class="col-6">
<input asp-for="productList" id="inputProducts" type="hidden" />
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label id="clientName"></label>
</div>
<div class="col-6">
<input asp-for="clientName" id="inputName" type="text" />
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label id="clientAddress"></label>
</div>
<div class="col-6">
<input asp-for="clientAddress" id="inputAddress" type="text" />
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label id="clientMail"></label>
</div>
<div class="col-6">
<input asp-for="clientMail" id="inputMail" type="text" />
</div>
</div>
<div class="form-group row">
<div class="col-3 offset-4">
<button class="btn btn-primary" id="orderB" asp-controller="SendItems" action="Save" type="submit">ORDER</button>
</div>
</div>
</form>
Also another issue is that if I don't use this piece of javascript the client is not redirected anymore to the "ThankYou" page :
var orderB = document.getElementById("orderB");
orderB.addEventListener("click", function () {
var inputName = document.getElementById("inputName").value;
var inputAddress = document.getElementById("inputAddress").value;
var inputMail = document.getElementById("inputMail").value;
var auxArray = [];
for (var i = 0; i < productsAux.length; i++) {
if (productsAux[i]!="") {
auxArray[i-1] = { "productName": productsAux[i].titlu, "productPrice": productsAux[i].pret, "quantity": localStorage.getItem(productsAux[i].titlu) };
}
}
document.getElementById("inputProducts").value = JSON.stringify(auxArray);
var shoppingCart = {
productList: auxArray,
clientName: inputName,
clientAddress: inputAddress,
clientMail: inputMail
};
$.ajax({
type: "POST",
data: JSON.stringify(shoppingCart),
url: "senditems/save",
contentType: "application/json;charset=utf-8",
})
})
Here is a demo worked:
Cart.cshtml(You need to change the bind of `productList,and then you don't need to use ajax to pass data to controller):
<form method="post" asp-controller="SendItems" asp-action="Save">
<div class="form-group row">
<div class="col-4">
<label id="clienId"></label>
</div>
<div class="col-6">
<input asp-for="id" id="idClient" type="hidden" />
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label id="clientProds"></label>
</div>
<div class="col-6">
#for (var i = 0; i < Model.productList.Count(); i++)
{
<input type="hidden" asp-for="#Model.productList[i].id" />
<input type="hidden" asp-for="#Model.productList[i].productName" />
<input type="hidden" asp-for="#Model.productList[i].productPrice" />
<input type="hidden" asp-for="#Model.productList[i].quantity" />
}
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label id="clientName"></label>
</div>
<div class="col-6">
<input asp-for="clientName" id="inputName" type="text" />
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label id="clientAddress"></label>
</div>
<div class="col-6">
<input asp-for="clientAddress" id="inputAddress" type="text" />
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label id="clientMail"></label>
</div>
<div class="col-6">
<input asp-for="clientMail" id="inputMail" type="text" />
</div>
</div>
<div class="form-group row">
<div class="col-3 offset-4">
<button class="btn btn-primary" id="orderB" type="submit" >ORDER</button>
</div>
</div>
</form>
Controller(SendItems):
[HttpPost]
public async Task<IActionResult> Save(ShoppingCart s)
{
return RedirectToAction("Index");
}
[HttpGet("~/ThankYou/Index")]
public IActionResult Index()
{
return View();
}
public IActionResult Cart()
{
ShoppingCart s = new ShoppingCart { id = 1, clientAddress = "address", clientName = "name1", clientMail = "123#123", productList = new List<Product> { new Product { id = 1, productName = "p1", productPrice = "10", quantity = "1" }, new Product { id = 2, productName = "p12", productPrice = "12", quantity = "3" } } };
return View(s);
}
result:
I was trying to create a popup system to create new data into the database. when I click"Create" in my index view then I find a popup form.but when I click "Save" for data save then it does not work anything. suddenly it works and saves the data into the database. but it happened just one time. but I don't understand why it's not working smoothly.
Here is my code:
Model
namespace Practise.Models
{
public class Category
{
public int Id { get; set; }
public string CategoryName { get; set; }
}
}
Controller:
namespace Practise.Controllers
{
public class CategoryController : Controller
{
private ApplicationDbContext _db;
public CategoryController(ApplicationDbContext db) //input parameter
{
_db = db;
}
public IActionResult Index()
{
return View(_db.Category.ToList());
}
[HttpGet]
public IActionResult Create()
{
Category ca = new Category();
return PartialView("_CreatePartial", ca);
//return View();
}
[HttpPost]
public IActionResult Create(Category ca)
{
_db.Category.Add(ca);
_db.SaveChanges();
return PartialView("_CreatePartial", ca);
}
}
}
Index.cshtml
#model IEnumerable<Practise.Models.Category>
#{
ViewData["Title"] = "Index";
}
<div id="PlaceHolderHere"></div>
<button type="button" class="btn btn-primary" data-toggle="ajax-model" data-target="#addEmployee" data-url="#Url.Action("Create")">Create</button>
</br></br>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Id)
</th>
<th>
#Html.DisplayNameFor(model => model.CategoryName)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.CategoryName)
</td>
<td>
<partial name="_ButtonPartial" model="#item.Id" />
</td>
</tr>
}
</tbody>
</table>
#section scripts{
<script src="//cdn.jsdelivr.net/npm/alertifyjs#1.13.1/build/alertify.min.js"></script>
<script type="text/javascript">
$(function(){
var save = '#TempData["save"]'
if (save!= null) {
alertify.success(save);
}
})
</script>
}
_CreatePartial view:
#model Category
<div class="modal fade" id="#addEmployee">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="#addEmployeeLabel">Add Category</h4>
<button type="button" class="close" data-dismiss="modal">
<span>x</span>
</button>
</div>
<div class="modal-body">
<form action="Create">
<div class="form-group">
<label asp-for="CategoryName"> </label>
<input asp-for="CategoryName" class="form-control" />
<span asp-validation-for="CategoryName" class="text-danger"></span>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-save="modal">Save</button>
</div>
</div>
</div>
</div>
JS(site.js)
$(function () {
var PlaceHolderElement = $('#PlaceHolderHere');
$('button[data-toggle="ajax-model"]').click(function (event) {
var url = $(this).data('url');
$.get(url).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
})
})
PlaceHolderElement.on('click', '[data-save="modal"]', function (event) {
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = form.serialize();
$.post(actionUrl, sendData).done(function (data) {
PlaceHolderElement.find('.modal').modal('hide');
})
})
})
My Output:
when I press the save button I want it to save the data to DB.but it does not work.
I have to change something like that for save data:
public IActionResult Create()
{
//Category ca = new Category();
//return PartialView("_CreatePartial", ca);
return View();
}
[HttpPost]
public IActionResult Create(Category ca)
{
_db.Category.Add(ca);
_db.SaveChanges();
return RedirectToAction("Index");
}
Create View:
#model Practise.Models.Category
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<div class="modal fade" id="#addEmployee">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="#addEmployeeLabel">Add Category</h4>
<button type="button" class="close" data-dismiss="modal">
<span>x</span>
</button>
</div>
<div class="modal-body">
<form asp-action="Create" method="post">
<div class="form-group">
<label asp-for="CategoryName"> </label>
<input asp-for="CategoryName" class="form-control" />
<span asp-validation-for="CategoryName" class="text-danger"></span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
#*<button type="button" class="btn btn-primary" data-save="modal">Save</button>*#
<input type="submit" class="btn btn-primary" value="Submit"/>
</div>
</form>
</div>
</div>
</div>
</div>
then successfully will save data.
View data not passing to controller. Please note I am using Entity Framework.
Trying to set the values of the Jobcard so that I can save them, but the fields are not binding to the model. Please any help would be appreciated in helping me solve this issue.
View Cshtml
#model Amax.Models.Jobcard
#using (Html.BeginForm("SaveJobcard", "Home", FormMethod.Post))
{
#Html.EditorFor(model => model.Email)
}
<input class="btn btn-sm btn-outline-success type="submit" id="submit" value="Create Jobcard" onclick="location.href='#Url.Action("SaveJobcard", "Home" , FormMethod.Post)'" />
HomeController
[System.Web.Http.HttpPost]
public ActionResult SaveJobcard(Jobcard Jobcard)
{
if (ModelState.IsValid)
{
try
{
}
catch (Exception ex)
{
}
}
return View();
}
DBModel
namespace Amax.Models
{
using System;
using System.Collections.Generic;
public partial class Jobcard
{
public long JCId { get; set; }
public Nullable<long> ClientId { get; set; }
public Nullable<long> ContactId { get; set; }
public string ContactNo { get; set; }
public string Email { get; set; }
public string VatNo { get; set; }
public Nullable<bool> SLA { get; set; }
public string Address { get; set; }
public Nullable<System.DateTime> TofOrder { get; set; }
public Nullable<System.DateTime> TofCompletion { get; set; }
public Nullable<long> ClientSigId { get; set; }
public string CSignature { get; set; }
public Nullable<System.DateTime> ClientSigDate { get; set; }
public Nullable<long> USigId { get; set; }
public string USignature { get; set; }
public string USigDate { get; set; }
public Nullable<int> StatusId { get; set; }
public List<JobCardItem> Item { get; set; }
}
//public JobCardItem()
//{
// Item = new List<JobCardItem>();
//}
}
View Model
namespace Amax.Models
{
public class ViewModel
{
public Jobcard Jobcard { get; set; }
public Client Client { get; set; }
public Contact Contact { get; set; }
public JobCardItem JobCardItem { get; set; }
public Status Status { get; set; }
public User Users { get; set; }
}
}
Jobcard Object empty
Fields Populated on form
Form Submit Network tab details
Adding in the full view html code
#using (Html.BeginForm("SaveJobcard", "Home", FormMethod.Post))
{
<div class="col-md-12 col-sm-12" id="JobCard">
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="row">
<div class="col-md-6 col-sm-6">
<label class="label" style="color:black;">Company Name :</label>
</div>
<div class="col-md-6 col-sm-6">
<select class="form-control" id="ClientId" value="ClientId">
#{
<option value="0">
Please Select
</option>
var Clients = ((Amax.Controllers.HomeController)this.ViewContext.Controller).GetClients();
foreach (var client in Clients)
{
<option onclick="#Url.Action("GetContacts", "Home", new RouteValueDictionary(new { id = #client.ClientId }));" value="#client.ClientId">
#client.ClientName
</option>
}
}
</select>
</div>
</div>
<br />
<div class="row">
<div class="col-md-6 col-sm-6">
<label class="label" style="color:black;">Contact No :</label>
</div>
<div class="col-md-6 col-sm-6">
<input type="text" class="form-control" id="ContactNo" name="ContactNo" />
</div>
</div>
<br />
<div class="row">
<div class="col-md-6 col-sm-6">
<label class="label" style="color:black;">Vat No :</label>
</div>
<div class="col-md-6 col-sm-6">
<input type="text" class="form-control" id="VatNo" name="VatNo" />
</div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="row">
<div class="col-md-6 col-sm-6">
<label class="label" style="color:black;">Contact Person :</label>
</div>
<div class="col-md-6 col-sm-6">
<select class="form-control" id="ContactId" name="ContactId">
<option value="0">
Please Select
</option>
</select>
</div>
</div>
<br />
<div class="row">
<div class="col-md-6 col-sm-6">
<label class="label" style="color:black;">Email</label>
</div>
<div class="col-md-6 col-sm-6">
#Html.EditorFor(model => model.Email)
</div>
</div>
<br />
<div class="row">
<div class="col-md-6 col-sm-6">
<label class="label" style="color:black;">SLA :</label>
</div>
<div class="col-md-3 col-sm-3">
<input type="checkbox" class="form-control" />
</div>
<div class="col-md-3 col-sm-3">
<input type="checkbox" class="form-control" />
</div>
</div>
</div>
</div>
<br />
<div class="row">
<div class="col-md-12 col-sm-12">
<div class="row">
<div class="col-md-3 col-sm-3">
<label class="label" style="color:black;">Address :</label>
</div>
<div class="col-md-9 col-sm-9">
<input type="email" class="form-control" id="Address" name="Address" />
</div>
</div>
</div>
</div>
<br />
<div class="row">
<div class="col-md-12 col-sm-12">
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="row">
<div class="col-md-6 col-sm-6"> <label class="label" style="color:black;">Time & Date of Order :</label></div>
<div class="col-md-6 col-sm-6"><input type="date" /> </div>
</div>
</div>
<div class="col-md-6">
<div class="row">
<div class="col-md-6 col-sm-6"> <label class="label" style="color:black;">Time & Date of Completion :</label></div>
<div class="col-md-6 col-sm-6"><input type="date" /></div>
</div>
</div>
</div>
</div>
</div>
<br />
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="row">
<div class="col-md-6 col-sm-6">
<label class="label" style="color:black;">Assigned Person :</label>
</div>
<div class="col-md-6 col-sm-6">
<select class="form-control" id="assigned" name="assigned">
#{
<option value="0">
Please Select
</option>
var Users = ((Amax.Controllers.HomeController)this.ViewContext.Controller).GetUsers();
foreach (var user in Users)
{
<option value="#user.UserId">
#user.UserName #user.Surname
</option>
}
}
</select>
</div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="row">
<div class="col-md-6 col-sm-6">
<label class="label" style="color:black;">Status :</label>
</div>
<div class="col-md-6 col-sm-6">
<select class="form-control" id="StatusId" name="StatusId">
#{
<option value="0">
Please Select
</option>
var Status = ((Amax.Controllers.HomeController)this.ViewContext.Controller).GetStatus();
foreach (var status in Status)
{
<option value="#status.Id">
#status.Status1
</option>
}
}
</select>
</div>
</div>
</div>
</div>
<input class="btn btn-sm btn-outline-success type="submit" id="submit" value="Create Jobcard" onclick="location.href='#Url.Action("SaveJobcard", "Home" , FormMethod.Post)'" />
<br />
<br />
<br />
<div class="row">
<div class="col-md-12 col-sm-12">
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="row">
<div class="col-md-4"> <label class="label" style="color:black;">#</label></div>
<div class="col-md-8"> <label class="label" style="color:black;">Description</label></div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="row">
<div class="col-md-6"> <label class="label" style="color:black;">Unit Price</label></div>
<div class="col-md-6"> <label class="label" style="color:black;">Total</label></div>
</div>
</div>
</div>
<div class="row" id="JobItems">
#Html.EditorFor(model => model.Item)
</div>
<div class="col-md-2 col-sm-2"> <button class="btn btn-sm btn-success" id="btnAdd"> + </button> <button class="btn btn-sm btn-danger" id="remove_1"> - </button></div>
<br />
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="row">
<div class="col-md-4">
</div>
<div class="col-md-8"></div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="row">
<div class="col-md-6 col-sm-6">Total</div>
<div class="col-md-6 col-sm-6"><label id="Jc_total">R 0.00</label></div>
</div>
</div>
</div>
<br />
<div class="row">
<div class="col-md-12 col-sm-12">
Terms:<br />
1. All equipment remains the property of AMAX until fully paid and client acknowledges that AMAX reserves the right to remove the equipment in the absence of payment.<br />
Client acknowledges that the equipment belongs to AMAX until fully paid and that the client shall not, under any circumstances, alienate, tarnish, destroy or erode the equipment.<br />
Client shall also ensure reasonable use of the equipment and shall ensure that the equipment is not exposed to negative elements which could alienate, tarnish, destroy or erode the goods.<br />
2. Customer agrees that AMAX may remove equipment if not paid within 7 working days of job completion.<br />
3. Customer will allow AMAX access to installation site to remove equipment that is unpaid.<br />
4. All Equipment carries a 1 year manufacturer’s guarantee.<br />
5. The Customer Agrees that the job has been done to his or her satisfaction
</div>
</div>
<br />
<div class="row">
<div class="col-md-12 col-sm-12">
<div class="row">
<dic class="col-md-12 col-sm-12">
Banking Details: Bank: Acc Name: Acc No: Branch Code: Type:
FNB Amax Electronics 623402 97028 251045 Cheque
Proof of payment: Mail accounts#amaxelectronics.co.za Fax: 012 543 2394
Ref: JN Number
</dic>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-sm-12 pull-right">
#using (Html.BeginForm("PDF", "Home", FormMethod.Post))
{
<input type="hidden" name="Styles" id="Styles" />
<input type="hidden" name="ExportData" id="ExportData" />
<input type="submit" id="btnSubmit" value="Generate PDF" />
}
#*<button class="btn btn-sm btn-outline-primary" onclick="#Url.Action("PDF", "Home")">Generate PDF</button>*#
</div>
</div>
}
```
Try binding the form values to the parameter in your controller
public ActionResult SaveJobcard([FromForm]Jobcard jobcard)
the solution to the problem was that one has to add form Html tags to wrap inside the
html you want to submit
Wrong
#using (Html.BeginForm("SaveJobcard", "Home", FormMethod.Post))
{
<div class="col-md-12 col-sm-12" id="JobCard">
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="row">
<div class="col-md-6 col-sm-6">
<label class="label" style="color:black;">Company Name :</label>
</div>
<div class="col-md-6 col-sm-6">
<select class="form-control" id="ClientId" value="ClientId">
#{
<option value="0">
Please Select
</option>
var Clients = ((Amax.Controllers.HomeController)this.ViewContext.Controller).GetClients();
foreach (var client in Clients)
{
<option onclick="#Url.Action("GetContacts", "Home", new RouteValueDictionary(new { id = #client.ClientId }));" value="#client.ClientId">
#client.ClientName
</option>
}
}
</select>
</div>
</div>
</div>
</div>
</div>
}
Works Perfect
#using (Html.BeginForm("SaveJobcard", "Home", FormMethod.Post))
{
<form>
<div class="col-md-12 col-sm-12" id="JobCard">
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="row">
<div class="col-md-6 col-sm-6">
<label class="label" style="color:black;">Company Name:</label>
</div>
<div class="col-md-6 col-sm-6">
<select class="form-control" id="ClientId" value="ClientId">
#{
<option value="0">
Please Select
</option>
var Clients = ((Amax.Controllers.HomeController)this.ViewContext.Controller).GetClients();
foreach (var client in Clients)
{
<option onclick="#Url.Action("GetContacts", "Home", new RouteValueDictionary(new { id = #client.ClientId }));" value="#client.ClientId">
#client.ClientName
</option>
}
}
</select>
</div>
</div>
</div>
</div>
</div>
</form>
}