Asp.Net MVC5 dropzone js send with paramters - asp.net-mvc

I want to post to a controller using bs-stepper and dropzone js together. How can I capture data in Controller?
html page, script and entity class and controller are below. I wonder where am I doing wrong
my scripts
document.getElementById("dropzone-yukle").addEventListener("click", function (event) {
event.preventDefault();
const form = document.getElementById('stepper-form');
formData = new FormData(form);
var object = {};
formData.forEach(function (value, key) {
object\[key\] = value;
});
var jsonData = JSON.stringify(object);
let params = { model: jsonData };
myDropzone.options.params = params;
myDropzone.processQueue();
});
Controller
[HttpPost]
public ActionResult OdaForm(ent_ODALAR model, HttpPostedFileBase[] files)
{
}
Entity class
public class ent_ODALAR
{
public long id { get; set; }
public int oda_no { get; set; }
public string oda_adi { get; set; }
public string oda_aciklamasi { get; set; }
public string oda_turu { get; set; }
public double oda_fiyati { get; set; }
public int oda_max_sayisi { get; set; }
public string oda_durumu { get; set; }
public int sira { get; set; }
public bool durum { get; set; }
public string oda_resim { get; set; }
}

Related

How create view for show cookie's info in asp.net mvc using razor?

I'm developing an online store using asp.net mvc 5 and I used cookie for add goods to cart . I want to have a page to show selected items (in cookie) and I don't know how do it, I just wrote an action result for it named Basket . I should use #model List<BasketVM> in my view but when don't know how ?!
could anyone help me please ?
Thanks
GoodController
[HttpGet]
public ActionResult Basket()
{
GoodDetailsRepositories blGoodDetails = new GoodDetailsRepositories();
List<BasketVM> listBasket = new List<BasketVM>();
List<HttpCookie> lst = new List<HttpCookie>();
for (int i = Request.Cookies.Count - 1; i >= 0; i--)
{
if (lst.Where(p => p.Name == Request.Cookies[i].Name).Any() == false)
lst.Add(Request.Cookies[i]);
}
foreach (var item in lst.Where(p => p.Name.StartsWith("NishtmanCart_")))
{
listBasket.Add(new BasketVM {
GoodDetails = blGoodDetails.Find(Convert.ToInt32(item.Name.Substring(13))), Count =Convert.ToInt32(item.Value) });
}
return View(listBasket);
}
BasketVM.cs
public class BasketVM
{
public NP1.Models.GoodDetail GoodDetails { get; set; }
public int Count { get; set; }
}
GoodDetails.cs
public partial class GoodDetail
{
public GoodDetail()
{
this.FactorItems = new HashSet<FactorItem>();
}
public int DetailsGoodID { get; set; }
public int FKSubGoods { get; set; }
public string NishtmanCode { get; set; }
public string DetailsColor { get; set; }
public string DetailsExist { get; set; }
public long DetailsNowPrice { get; set; }
public Nullable<long> DetailsPrePrice { get; set; }
public string DetailsName { get; set; }
public string DetailsLeatherType { get; set; }
public string DetailsWeight { get; set; }
public string DetailsSize { get; set; }
public string DetailsProducer { get; set; }
public string DetailsExtraInfo { get; set; }
public string DetailsURL { get; set; }
public string DetailsKeyWords { get; set; }
public string DetailsTags { get; set; }
public int DetailsLike { get; set; }
public int DetailsDisLike { get; set; }
public string DetailsImage1 { get; set; }
public string DetailsSmallImage1 { get; set; }
public string DetailsImage2 { get; set; }
public string DetailsSmallImage2 { get; set; }
public string DetailsImage3 { get; set; }
public string DetailsSmallImage3 { get; set; }
public string DetailsImage4 { get; set; }
public string DetailsSmallImage4 { get; set; }
public virtual SubGood SubGood { get; set; }
public virtual ICollection<FactorItem> FactorItems { get; set; }
}
Add to cart code
public ActionResult AddToCart (int Id , int Count)
{
try
{
if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
{
//Edit cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), (Convert.ToInt32(Request.Cookies["NishtmanCart_" + Id.ToString()].Value) + 1).ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Set(cookie);
}
else
{
//Add new cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), Count.ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
}
List<HttpCookie> lst = new List<HttpCookie>();
for (int i = 0; i < Request.Cookies.Count; i++ )
{
lst.Add(Request.Cookies[i]);
}
bool isGet = Request.HttpMethod == "GET";
int CartCount = lst.Where(p => p.Name.StartsWith("NishtmanCart_") && p.HttpOnly != isGet).Count();
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("Good added successfully", MessageType.Success).Script,
Html = "cart items (" + CartCount.ToString() + ")"
}
);
}
catch(Exception)
{
return Json(new MyJsonData()
{
Success = false,
Script = "alert('Good didn't add');",
Html = ""
}
);
}
}
with what name you are saving the cookies you can retrieve like this let say userid u want to get rest what you have wriiten will work:
if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Userid"))
{
HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Userid"];
// retrieve cookie data here
}
how to call in view :
Viewbag.userid = #Request.Cookies["Userid"].value
In order to read a cookie client-side it needs to be created with the HttpOnly flag set to false.
Please go thorugh the below already asked question.
MVC Access stored cookie

Sending List<Freight> to controller in ASP.net MVC using AngularJS

I need to send a JSON object which is a List<Freight> from the view to the controller.
How can I do this.
The class is:
public class Freights
{
public string Name { get; set; }
public string ListName { get; set; }
public decimal Price { get; set; }
public decimal PostPaidCost { get; set; }
public string DisplayPrice { get; set; }
public bool Active { get; set; }
public string Description { get; set; }
public string Transport { get; set; }
public string Instance { get; set; }
}
I tried out the following but it didn't work.
I need to send List<Freights> which is stored in Freights in the below code.
$http.post('/Customization/FreightItems_update?Freights='
+ Freights + '&CustomerGuid=' + CustomerGuid).success(function (result) {
...
});
Controller:
public JsonResult FreightItems_update(List<Freights> Freights, Guid CustomerGuid)
{
}
I even tried to get the data as object and cast it but it didn't work.
// _Freights = aray of Freights
//_CustomerGuid = CustomerGuid
var myObject = {
Freights: _Freights,
CustomerGuid: _CustomerGuid
};
$http.post('/Customization/FreightItems_update', myObject)
.then(
function () { alert('ok')}
, function () {alert('can't post') }
);
option 2
$http.post('/Customization/FreightItems_update',
{Freights: _Freights, CustomerGuid: _CustomerGuid})
.then(
function () { alert('ok')}
, function () {alert('can't post') }
);

MVC Code- or Model First

Most of the tutorials for MVC with Entity Framework are centered around Code-First, where you write classes for generating the model. This gives the advantage of control and Migrations, but I think it lack overview. I would therefore prefer to create the model using the graphical designer, but I cannot see how or if data migrations work in this context. It seems, that when I change the model (with data in the database), all the data is deleted in all tables.
Is there a way around this?
How can I do validation when using Model-First? Partial classes?
you may use the global validation beside mvc validation
example :
public class ValidationCriteria
{
public ValidType Type { get; set; }
public ValidRange Range { get; set; }
public ValidFormat Format { get; set; }
public ValidIsNull IsNull { get; set; }
public ValidCompare Compare { get; set; }
public ValidDB DB { get; set; }
public string Trigger { get; set; }
public Dictionary<string, ValidationCriteria> Before { get; set; }
public string After { get; set; }
public class ValidDB
{
public string functionName { get; set; }
public object[] param { get; set; }
public object functionClass { get; set; }
public string msg { get; set; }
public bool check = false;
}
public class ValidCompare
{
public string first { get; set; }
public string second { get; set; }
public string compareOperator { get; set; }
public string compareValue { get; set; }
public string msg { get; set; }
public bool check = false;
}
public ValidationCriteria()
{
this.Range = new ValidRange();
this.Format = new ValidFormat();
this.IsNull = new ValidIsNull();
this.Type = new ValidType();
this.Compare = new ValidCompare();
this.DB = new ValidDB();
this.Trigger = "blur";
this.Before = new Dictionary<string, ValidationCriteria>();
this.After = "";
}
public class ValidType
{
// checking element is integer.
public bool isInt { get; set; }
// checking element is decimal.
public bool isDecimal { get; set; }
public string msg { get; set; }
public bool check = false;
}
public class ValidRange
{
public long min { get; set; }
public long max { get; set; }
public string msg { get; set; }
public bool check = false;
}
public class ValidFormat
{
public bool isEmail { get; set; }
public string regex { get; set; }
public string msg { get; set; }
public bool check = false;
}
public class ValidIsNull
{
public string nullDefaultVal { get; set; }
public string msg { get; set; }
public bool check = false;
}
}
Meanwhile you may use validation part in your controller
Example :
private bool validateMaintainanceManagement(MaintainanceCRUD.Maintainance model, bool edit = false, bool ServerValidation = true)
{
bool ValidModel = false;
Dictionary<string, ValidationCriteria> validCriteria = new Dictionary<string, ValidationCriteria>();
#region maintainTitle Criteria
ValidationCriteria maintainTitle = new ValidationCriteria();
maintainTitle.IsNull.msg = Resources.Home.ErrmaintainTitle;
maintainTitle.IsNull.check = true;
maintainTitle.IsNull.nullDefaultVal = "-1";
//maintainTitle.Trigger = "change"; // this may trigger if you are using dropdown
validCriteria.Add("maintainTitle", maintainTitle);
#endregion

Serialize Form GetJSON returns null model

I have a form I am trying to send in a GetJSON call. When I get to the Controller the model that si tied to the view is a null vlaue. I have had issues before dealign with returning data when I woudl get an empy object but never a null value. Below is the code I am using to send the form
var cqvdata = $("form").serialize();
$.getJSON('#Url.Action("GetEmailByAdvanced", "CustomerEmails")', { cqv: cqvdata }, function (contacts) {
var emails = "";
$.each(contacts, function (index, contact) {
$('#BCCText').tagit('createTag', contact.Email)
});
return false;
});
Below is what I have on the controller side
public JsonResult GetEmailByAdvanced(MassEmailViewModel cqv)
{
}
Here is what I get for results if I turn my argument into a string
"EmailFromAddressID=1&ToAddresses=&CCAddresses=bclairmont%40harr.com&BCCAddresses=adunn%40harr.com&Subject=&Body="
Below is the MassEmailViewModelClass and all sub classes
public class MassEmailViewModel
{
public MassEmailViewModel()
{
ComplexQuery = new CustomerQueryViewModel();
}
public int EmailFromAddressID { get; set; }
public CustomerQueryViewModel ComplexQuery { get; set; }
public string ToAddresses { get; set; }
public string CCAddresses { get; set; }
public string BCCAddresses { get; set; }
public string Subject { get; set; }
[AllowHtml]
public string Body { get; set; }
}
public class CustomerQueryViewModel
{
public CustomerQueryViewModel()
{
Products = new List<CustomerProductQueryProduct>();
Details = new List<CustomerQueryDetail>();
}
public Boolean IncludeOnAll { get; set; }
public Boolean ExcludeOnAll { get; set; }
public List<CustomerProductQueryProduct> Products { get; set; }
public List<CustomerQueryDetail> Details { get; set; }
}
public class CustomerProductQueryProduct
{
public CustomerProductQueryProduct()
{
ProductDetails = new List<CustomerProductQueryProductDetail>();
ProductVersions = new List<ProductVersion>();
}
public ProductType ProductType { get; set; }
public Boolean Exclude { get; set; }
public Boolean Include { get; set; }
public int VersiondID { get; set; }
public List<CustomerProductQueryProductDetail> ProductDetails { get; set; }
public List<ProductVersion> ProductVersions { get; set; }
}
public class CustomerProductQueryProductDetail
{
public ProductTypeDetail ProductDetail { get; set; }
public Boolean Exclude { get; set; }
public Boolean Include { get; set; }
public string Value { get; set; }
public string Value2 { get; set; }
}
public class CustomerQueryDetail
{
public string Description { get; set; }
public string Type { get; set; }
public Boolean Exclude { get; set; }
public Boolean Include { get; set; }
public string Value { get; set; }
public string Value2 { get; set; }
}
The only thing not being returned is my ComplexQuery in the serialize because I am using a JQuery dialog so it takes those elements out of the form. I woudl think I woudl get a MassEmaikViewModel with all the vlaues but ComplexQuery and have a null for that but I just get a null as iff the argument never even got initialized.
Any ideas on what could be causing this?
One other thing and I don't know if this will help give anyone any insight or not but I can post from the form and have the MassEmailViewModel as the argument in the post and it works fine filling out all the values except for ComplexQuery
I figured it out after a ton of trial and error. It seems like GetJSON can't handle passing the data. What I did to correctly get information was to change to an AJAX get call. I will post the code below
$.ajax({
url: '#Url.Action("GetEmailByAdvanced", "CustomerEmails")',
type: 'GET',
data: cqvdata,
success: function (data) {
//called when successful
var emails = "";
$.each(contacts, function (index, contact) {
$('#BCCText').tagit('createTag', contact.Email)
});
return false;
},
error: function (e) {
//called when there is an error
//console.log(e.message);
}
});
I used the exact data I had in the GetJSON. In fact I commented out the GetJSON and just put this in below it and I got my model filled in on the controller side.

Sending JSON object to my Ajax method in a controlelr

I am trying to call a method in my controller using ajax and passing an object. I can do this very well when it comes to variables but can't seem to do it using an object. The method is called fine, but the object values are always null. I have also tried using .toJSON method but get this error Uncaught TypeError: Object function (a,b){return new d.fn.init(a,b,g)} has no method 'toJSON' , yes, I have JSON2 included
Here is my attempt so far:
var VoucherDetails = this.GetVoucherDetails();
$.post("/Vouchers/GetVoucherPreviewTemplate", { "Voucher": VoucherDetails},
function (data) {
});
function GetVoucherDetails()
{
var teet = $("#Title").val();
return { Title: teet };
}
C#
[HttpPost]
public ActionResult GetVoucherPreviewTemplate(ENT_Voucher Voucher)
{
return Json("");
}
Here is my ENT_Voucher code:
[Serializable]
public class ENT_Voucher : ENT_VoucherEntityBase
{
public int BusinessID { get; set; }
public int? SiteID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Code { get; set; }
public string Link { get; set; }
public DateTime StartDate { get; set; }
public DateTime ExpiryDate { get; set; }
public string ImageLink { get; set; }
public int Status { get; set; }
public ENT_Business BusinessDetails { get; set; }
public string VoucherTandC { get; set; }
public int Type { get; set; }
public string DaysRemaining { get; set; }
public int RequestCount { get; set; }
public bool IsPetoba { get; set; }
public ENT_Voucher()
{
this.BusinessDetails = new ENT_Business();
}
}
You could send it as a JSON request which allows you to send arbitrarily complex objects:
var VoucherDetails = this.GetVoucherDetails();
$.ajax({
url: '#Url.Action("GetVoucherPreviewTemplate", "Vouchers")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ voucher: VoucherDetails }),
success: function(result) {
}
});
If you have JSON2.js included then you want to use JSON.stringify() and pass it the data to serialize in your AJAX call!

Resources