insert values through jquery to c# mvc post method - c#

I'm new to this and got stuck between these codes without getting inserted. Can anybody pls tell me the issue in my post method.
jquery
$.post("Create", { REG_NO : $("#text1").val(), REG_DATE : $("#text2").val() }, function (data) {
alert("done");
});
CarsController (controller file)
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,REG_NO,REG_DATE")] Car car)
{
if (ModelState.IsValid)
{
db.Cars.Add(car);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(car);
}
}
class file
public class Car
{
public int ID { get; set; }
public string REG_NO { get; set; }
public DateTime REG_DATE { get; set; }
}

$.post(
'/controller/action',
{ field_a: "Value a", field_b: "Value b" },
function(data) {
$('#result').html(data);
}
);

Related

Form-data is not binding to viewmodel with a generic type

I have an application written using C# on the top of ASP.NET Core 5.0.
I have the following view-model
public class TestVM
{
public Name { get; set; }
public MenuViewModel<string> State { get; set;}
public TestVM()
{
State = MenuViewModel<string>();
}
}
Here is a stripped down version of my MenuViewModel
public class MenuViewModel
{
[BindNever]
public IEnumerable<SelectListItem> Items { get; set; }
}
public class MenuViewModel<T> : MenuViewModel
{
public T Value { get; set; }
}
The problem, is when the post request comes in, the viewModel.State.Value is null. When I evaluate Request.Form I do see the key State.Value with the correct value of CA
Here is a stripped down of my action method in the controller.
[HttpPost, ValidateAntiForgeryToken]
public IActionResult Store(TestVM viewModel)
{
if(ModelState.IsValid)
{
// do some
}
return View(viewModel);
}
How can I bind the form data from the request to State.Value property correctly?
Updated I created an editor-template to allow me to render the MenuVieModel. The ~/Views/Shared/EditorTemplates/MenuViewModel.cshtml contains the following code
#model dynamic
#{
if (!(Model is MenuViewModel m))
{
return;
}
dynamic obj = new System.Dynamic.ExpandoObject();
obj.Class = "form-control";
if (Html.ViewData.ModelMetadata.IsRequired)
{
obj.Required = true;
}
}
#Html.DropDownList("Value", m.Options, Html.ViewData.ModelMetadata.Placeholder, obj)
Firsly,you need know that for each property of the complex type, model binding looks through the sources for the name pattern prefix.property_name. If nothing is found, it looks for just property_name without the prefix.
Here is a working demo you could follow:
Model:
public class TestVM
{
public string Name { get; set; }
public MenuViewModel<string> State { get; set; }
public TestVM()
{
State =new MenuViewModel<string>();
}
}
public class MenuViewModel
{
[BindNever]
public IEnumerable<SelectListItem> Items { get; set; }
}
public class MenuViewModel<T> : MenuViewModel
{
public T Value { get; set; }
}
View:
#model dynamic
#{
if (!(Model is MenuViewModel m))
{
return;
}
dynamic obj = new System.Dynamic.ExpandoObject();
obj.Class = "form-control";
if (Html.ViewData.ModelMetadata.IsRequired)
{
obj.Required = true;
}
}
<form asp-action="Store">
#*change here,And I do not find Options in your MenuViewModel,So I change it to Items*#
#Html.DropDownList("State.Value", m.Items, Html.ViewData.ModelMetadata.Placeholder, obj)
<input type="submit" value="post" />
</form>
Controller:
public IActionResult Index()
{
var model = new MenuViewModel<string>()
{
Items = new List<SelectListItem>() {
new SelectListItem() { Value = "-1", Text = "--- Select ---" },
new SelectListItem() { Value = "org1", Text = "org1" },
new SelectListItem() { Value = "org2", Text = "org2" },
new SelectListItem() { Value = "org3", Text = "org3" }
}
};
return View(model);
}
[HttpPost, ValidateAntiForgeryToken]
public IActionResult Store(TestVM viewModel)
{
if (ModelState.IsValid)
{
// do some
}
return View(viewModel);
}
Result:

How to get each value from table in ASP.NET MVC?

I get each value but it doesn't display on DSChiTiet. How can I fix it? It only gets value TenKH, NgayLap, TongTien.
DSChiTiet doesn't get value from table and displays null. enter image description here
Thank you very much for your help <3.
My model PhieuBanHangModel
public class PhieuBanHangViewModel
{
public int MaPBH { get; set; }
public string TenKH { get; set; }
public DateTime NgayLap { get; set; }
public decimal TongTien { get; set; }
public IEnumerable<CT_PhieuBanHangViewModel> DSChiTiet { get; set; }
}
My model CT_PhieuBanHangModel
public class CT_PhieuBanHangViewModel
{
public int MaPBH { get; set; }
public int MaSP { get; set; }
public int SoLuong { get; set; }
public decimal DonGia { get; set; }
public decimal ThanhTien { get; set; }
}
Controller Create Json
[HttpPost]
public JsonResult Create(PhieuBanHangViewModel phieuBanHang)
{
return Json(data: "", JsonRequestBehavior.AllowGet);
}
Function in View
function ThanhToan() {
var phieuBanHang = {};
var dsct_PhieuBanHang = new Array();
phieuBanHang.TenKH = $("#txtTenKH").val();
phieuBanHang.NgayLap = $("#txtNgayGiaoDich").val();
phieuBanHang.TongTien = $("#txtTongTien").val();
$("table tr:not(:first)").each(function () {
var ct_PhieuBanHang = {};
ct_PhieuBanHang.MaSP = parseFloat($(this).find("td:eq(0))").text());
ct_PhieuBanHang.SoLuong = parseFloat($(this).find("td:eq(4))").text());
ct_PhieuBanHang.DonGia = parseFloat($(this).find("td:eq(6))").text());
ct_PhieuBanHang.ThanhTien = parseFloat($(this).find("td:eq(7))").text());
dsct_PhieuBanHang.push(ct_PhieuBanHang);
});
phieuBanHang.DSChiTiet = dsct_PhieuBanHang;
$.ajax({
async: true,
type: 'POST',
dataType: 'JSON',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(phieuBanHang),
url: '/Manager/CT_PhieuBanHang/Create',
success: function (data) {
},
error: function () {
alert('Lỗi');
}
});
}
You may need to inherit ApiControllerand add the [FromBody] attribute to the binding model:
public class MyController : ApiController
{
/* something else... */
// /Manager/CT_PhieuBanHang/Create
[HttpPost]
public JsonResult Create([FromBody] PhieuBanHangViewModel phieuBanHang)
{
return Json(data: "", JsonRequestBehavior.AllowGet);
}
/* something else... */
}
For your jQuery code, make sure thet:$("table tr:not(:first)") do returns an array contains at least 1 item. (You can verify that by doing a console.log(phieuBanHang) to print out your data).

How to deserialize a JSON object?

I am working on Website in which front end is developed in Angular 7 . I am sending an array from angular in json format to c# asp.net core. I am getting data in below format
`First = {"model": [{
"_organization_Name": "erw",
"_designation": "dfs",
"_p_Start_Date": "2019-02-28T19:00:00Z",
"_p_End_Date": "2019-03-27T19:00:00Z"
},
{
"_organization_Name": "erwfg",
"_designation": "dfsfgfg",
"_p_Start_Date": "2019-02-28T19:00:00Z",
"_p_End_Date": "2019-03-27T19:00:00Z"
}
]
}`
My Method in asp.net core below
[HttpPost("[action]")]
public IActionResult SaveProfessional([FromBody]JObject prof)
{
var obj = new Candidate_Professional_Info_Table(_context);
obj.Identity_Number = 112131.ToString();
obj =
JsonConvert.DeserializeObject<Candidate_Educational_Info_Table>(prof);
var result = obj.SaveProfessional(prof);
return Ok(new { suces = "result" });
}
My code is not deserializing json object Any solution please as now I have spend one week in this problem. My c# model is given below
public int ID { get; set; }
public string Identity_Number { get; set; }
[Required]
[RegularExpression("^[a-zA-Z0-9]+$", ErrorMessage = "Organization Name Not Valid")]
public string Organization_Name { get; set; }
[Required]
[RegularExpression("^/d{1, 2}///d{1,2}///d{4}$")]
public DateTime? p_Start_Date { get; set; }
[RegularExpression("^/d{1, 2}///d{1,2}///d{4}$")]
public DateTime? p_End_Date { get; set; }
[Required]
[RegularExpression("^[a-zA-Z0-9]+$", ErrorMessage = "Designation Name Not Valid")]
public string Designation { get; set; }
public bool InProgress { get; set; }
[NotMapped]
public List<Candidate_Professional_Info_Table> listprof { get; set; }
[NotMapped]
private readonly RegConnString _Context;
public Candidate_Professional_Info_Table(RegConnString connString)
{
_Context = connString;
}
You have underscores before your properties thats why the JsonConvert cannot map properly.
You can use [JsonProperty("")] attributes to map to the correct property
your properties would look like then
[Required]
[RegularExpression("^[a-zA-Z0-9]+$", ErrorMessage = "Organization Name Not Valid")]
[JsonProperty("_organization_Name")]
public string Organization_Name { get; set; }
[Required]
[RegularExpression("^/d{1, 2}///d{1,2}///d{4}$")]
[JsonProperty("_p_Start_Date")]
public DateTime? p_Start_Date { get; set; }
[RegularExpression("^/d{1, 2}///d{1,2}///d{4}$")]
[JsonProperty("_p_End_Date")]
public DateTime? p_End_Date { get; set; }
[Required]
[RegularExpression("^[a-zA-Z0-9]+$", ErrorMessage = "Designation Name Not Valid")]
[JsonProperty("_designation")]
public string Designation { get; set; }
To handle for the rest. You have a root object called model. But all we want is the List<Candidate_Educational_Info_Table>
public IActionResult SaveProfessional([FromBody]JObject prof)
{
//select the model itself. Also do some nullchecking to prevent errors if empty
var fooModel = prof.First;
//select the content of the model(your actual array). Also do some nullchecking to prevent errors if empty
var fooObjectArray= fooModel.First;
var theDeserializedList = fooObjectArray.ToObject<List<Candidate_Educational_Info_Table>>();
foreach (var item in theDeserializedList)
{
//handle the rest of what you want to do.
//As i see you inject the context into the objects on create but this will not be possible if you use the deserialze.
//Its better to pass the context on the method SaveProfessional
}
return Ok(new { suces = "result" });
}
There are a variety of JSON serializers. The one i usually use is Newtonsoft Json
Movie m = JsonConvert.DeserializeObject<Movie>(json);
You can also use dynamic deserilaization, which can deserialise without a class definition. You can use System.Web.Script.Serialization to parse and get a dynamic object. It also requires System.Web.Extensions reference
JavaScriptSerializer js = new JavaScriptSerializer();
dynamic modelItems = js.Deserialize<dynamic>(json);
var cors = new EnableCorsAttribute("http://localhost:4200", "*", "*");
config.EnableCors(cors);
.Linq;
namespace MTBCTest.Controllers
{
[EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
public class UsersController : ApiController
{
private testingDbEntities db = new testingDbEntities();
// GET: api/Users
[HttpGet]
public IQueryable<User> GetUsers()
{
return db.Users;
}
// GET: api/Users/5
[ResponseType(typeof(User))]
[HttpGet]
public IHttpActionResult GetUser(int id)
{
User user = db.Users.Find(id);
if (user == null)
{
return NotFound();
}
return Ok(user);
}
// PUT: api/Users/5
[ResponseType(typeof(void))]
[HttpPost]
public IHttpActionResult PutUser(User user)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
User ob = db.Users.Find(user.ID);
ob.FirstName = user.FirstName;
ob.LastName = user.LastName;
ob.Password = user.Password;
ob.EmailID = user.EmailID;
db.Entry(ob).State = EntityState.Modified;
db.SaveChanges();
return Ok();
}
// POST: api/Users
[HttpPost]
public IHttpActionResult PostUser(User user)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.InserUser(user.FirstName,user.LastName,user.EmailID, user.Password);
db.SaveChanges();
return Ok();
}
// DELETE: api/Users/5
[HttpGet]
public IHttpActionResult DeleteUser(int id)
{
User user = db.Users.Find(id);
if (user == null)
{
return NotFound();
}
db.Users.Remove(user);
db.SaveChanges();
return Ok();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool UserExists(int id)
{
return db.Users.Count(e => e.ID == id) > 0;
}
}
}
export class User {
public FirstName: string;
public LastName: string;
public EmailID: string;
public Password: string;
}
import { Injectable } from '#angular/core';
import { HttpClientModule, HttpClient, HttpHeaders } from '#angular/common/http';
import {User} from '../user';
import { Observable } from 'rxjs';
import { convertActionBinding } from
'#angular/compiler/src/compiler_util/expression_converter';
#Injectable({
providedIn: 'root'
})
export class UserServiceService {
// tslint:disable-next-line:variable-name
constructor(private _http: HttpClient) { }
public SaveUser(api: string , userData: User): Observable<any> {
// tslint:disable-next-line:no-trailing-whitespace
return this._http.post<any>(api, userData, {
headers : new HttpHeaders({
'Content-Type' : 'application/json'
})
});
}
public DeleteUser(api: string , id: number): Observable<any> {
return this._http.get<any>(api , {
// headers : new HttpHeaders({
// 'Content-Type' : 'application/x-www-form-urlencoded'
// }),
params: {
id: id.toString()
}
});
}
public editUserByID(api: string, userData: User): Observable<any> {
return this._http.post<any>(api, userData , {
// headers: new HttpHeaders({
// 'Content-Type' : 'application/json'
// })
});
}
public GetUsers(api: string): Observable<User[]> {
return this._http.get<User[]>(api);
}
public GetUsersByID(api: string , ID: number): Observable<User> {
return this._http.get<User>(api, {
// headers: new HttpHeaders({
// 'Content-Type': 'application/x-www-form-urlencoded'
// }),
params: {
ID: ID.toString()
}
});
}
}
import { Component, OnInit, OnDestroy } from '#angular/core';
import {UserServiceService} from 'src/Models/Services/user-service.service';
import { User } from 'src/Models/user';
import { Subscription } from 'rxjs';
#Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit, OnDestroy {
subscriptions: Subscription [] = [];
userData: User;
users: User[];
ifinserted: boolean;
isEdited: boolean;
// tslint:disable-next-line:variable-name
constructor(private _userService: UserServiceService) { }
ngOnInit() {
this.userData = new User();
this.ifinserted = false;
this.isEdited = false;
}
saveUser(data: User) {
console.log(data);
this._userService.SaveUser('http://localhost:58649/api/Users/PostUser' , data)
.subscribe();
this.ifinserted = true;
alert('Inserted');
}
getUser() {
this._userService.GetUsers('http://localhost:58649/api/Users/GetUsers')
.subscribe((data: User[]) => {
this.users = data;
});
}
editUser(i: number) {
this.subscriptions.push(
this._userService.GetUsersByID('http://localhost:58649/api/Users/GetUser' , i)
.subscribe((data: User) => {
this.userData = data;
this.isEdited = true;
}));
}
editUserByID(obj: User) {
this._userService.editUserByID('http://localhost:58649/api/Users/PutUser' , obj)
.subscribe();
this.isEdited = false;
alert('Edited');
}
deleteUser(i: number) {
console.log(i);
this._userService.DeleteUser('http://localhost:58649/api/Users/DeleteUser' , i)
.subscribe();
alert('Deleted');
}
ngOnDestroy() {
this.subscriptions.forEach(s => s.unsubscribe());
}
}

How to check if duplicate data is present in the database using asp.net mvc

I want to show a message saying that the JourneyID already exists in the database.
The model is :
using System.Web.Mvc;
namespace Project_Final.Models
{
using System;
public partial class sp_FMS_Group6_Module3_ViewBonusMilesRequesttt_Result
{
public int RequestID { get; set; }
public Nullable<long> CustomerID { get; set; }
[Remote("Check", "Home", ErrorMessage = "Bonus Miles Request has already been sent!")]
public Nullable<int> JourneyID { get; set; }
public Nullable<System.DateTime> RequestDate { get; set; }
public string Status { get; set; }
}
}
The following are the actions in my controller :
[HttpPost]
public ActionResult Index(string Create)
{
FMS_Group6_Module3_BonusMilesRequestt objProd = new FMS_Group6_Module3_BonusMilesRequestt();
objProd.CustomerID = int.Parse(Request.Form["CustomerID"].ToString());
objProd.JourneyID = int.Parse(Request.Form["JourneyID"].ToString());
objProd.RequestDate = DateTime.Parse(Request.Form["RequestDate"].ToString());
objProd.Status = "Pending";
objDB.FMS_Group6_Module3_BonusMilesRequestt.Add(objProd);
int i = objDB.SaveChanges();
if (i > 0)
ViewBag.Message = "Product details saved successfully";
return Content("<script language='javascript' type='text/javascript'>alert('Your Bonus Miles Request has been successfully sent!');window.location='/Home/GetID'</script>");
//return Redirect("GetID");
}
public ActionResult Check(string Crreate)
{
FMS_Group6_Module3_BonusMilesRequestt objProd = new FMS_Group6_Module3_BonusMilesRequestt();
bool ifJourneyIDExist = false;
try
{
ifJourneyIDExist = Crreate.Equals(objProd.JourneyID) ? true : false;
return Json(!ifJourneyIDExist, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
Any kind of help would be greatly appreciated. Thanks.
Before you insert, you can check in the DB, if the JourneyID is exists.
if (objDB.FMS_Group6_Module3_BonusMilesRequestt.Any(x => x.JourneyID == objProd.JourneyID))
{
// Exists
}
LINQ query to make sure all values (ex enumerable) are not duplicated
var noDuplicationVariable = enumerableValues.GroupBy(a => a.Key).All(b => b.Count() == 1);
use it as an assertion condition before your function

Why Hidden Fields value are not posted in mvc 4?

In my MVC-4 application i take location from geolocation using javaScript and set latitude, longiture and accuracy in Hidden Fields. Values are set correctly in Hidden fields but during PostBack it shows null.
Here is my code :
Razor :
#using (Html.BeginForm()
{
#Html.HiddenFor(x => x.CurrentLocation.Latitude)
#Html.HiddenFor(x => x.CurrentLocation.Longitude)
#Html.HiddenFor(x => x.CurrentLocation.Accuracy)
<input type="submit" name="command" value="Start" />
}
JavaScript :
function SetLocation(position) {
console.log("{0},{1},{2}".format(position.coords.latitude, position.coords.longitude, position.coords.accuracy));
$("#CurrentLocation_Latitude").val(position.coords.latitude);
$("#CurrentLocation_Longitude").val(position.coords.longitude);
$("#CurrentLocation_Accuracy").val(position.coords.accuracy);
}
$(document).ready(function () {
$('form').submit(function () {
LocationService.getCurrentLocation(SetLocation);
});
});
But if I write this code then it`s work
$(document).ready(function () {
$('form').submit(function () {
$("#CurrentLocation_Latitude").val(100);
$("#CurrentLocation_Longitude").val(100);
});
});
This send proper value to the controller.
I don`t understand why this is happening.
Thank`s in advance.
Update 1 :
Model :
[ComplexType]
public class Location
{
public Location()
{
}
public Location(double latitude, double longiture, double? accuracy = null)
{
Latitude = latitude;
Longitude = longiture;
if (accuracy.HasValue)
Accuracy = accuracy.Value;
}
[DisplayName("Latitude : ")]
public double? Latitude { get; set; }
[DisplayName("Longitude : ")]
public double? Longitude { get; set; }
public double? Accuracy { get; set; }
}
public class ServiceInfoEditMetadata : ServiceInfo
{
public Int64 MachineId { get; set; }
[DisplayName("Client Name :")]
public string ClientName { get; set; }
[DisplayName("Site Name :")]
public string SiteName { get; set; }
public Location CurrentLocation { get; set; }
[DisplayName("Client Username :")]
public string ClientUsername { get; set; }
[DisplayName("Client Password :")]
public string ClientPassword { get; set; }
}
Controller :
public ActionResult Edit(Int64 id, ServiceInfoEditMetadata serviceInfoEditMetadata, string command)
{
try
{
switch (command)
{
case "Add":
AddMachineToServiceInfoDetails(serviceInfoEditMetadata);
return View(serviceInfoEditMetadata);
case "Start":
_serviceInfoService.StartService(serviceInfoEditMetadata, User.Identity.Name);
return RedirectToAction("Edit", serviceInfoEditMetadata.Id);
case "Update":
if (!ModelState.IsValid) return View(serviceInfoEditMetadata);
_serviceInfoService.UpdateServiceInfo(serviceInfoEditMetadata, User.Identity.Name);
return RedirectToAction("List");
}
return View(serviceInfoEditMetadata);
}
catch (Exception ex)
{
ModelState.AddModelError("ServiceInfoEditError", ex.Message);
return View(serviceInfoEditMetadata);
}
}
I assume your LocationService.getCurrentLocation is asynchronous. You should then delay form submission until it completes.
maybe you can try :
$(document).ready(function () {
var locationSet =false;
$('form').submit(function (event) {
if(!locationSet)
event.preventDefault();
LocationService.getCurrentLocation(
function(position){
SetLocation(position);
locationSet= true;
$('form').submit();
}
);
});
});
There could be more causes, because the mechanism (e.g mvc binding, ajax) of passing the fields' data is little complex.
I see that in the following js code you're passing handler to function 'SetLocation'. Try to invoke the function:
$(document).ready(function () {
$('form').submit(function () {
LocationService.getCurrentLocation(SetLocation(position));// 'SetLocation' with (position)
});
});

Categories

Resources