Sending null data from $.post to controller model - javascript

My Model -
public class Phasessfilter
{
public string Searchterm {get;set;}
public string ob1 {get;set;}
public string ob2 {get;set;}
public string ob3 {get;set;}
public List<string> ob4 { get; set; }
public List<string> ob5 { get; set; }
}
Controller -
public JsonResult GtRlts(Phasessfilter jop)
{
}
this is my script
var recr = "";
var study = "";
var results = "";
var phases1 = [];
var fund = [];
var values = { Searchterm: Searchterm, ob1: recr, ob2: study, ob3: results, ob4: phases1, ob5: fund }
$.post("GtRlts", values, function (abc) {
}
So i am getting values for Searchterm , ob1 ,ob2 ,ob3 but i am getting null values for ob4 and ob5 .why is List not taking the array values or am i doing something wrong .
P.S - i dont want to use $.ajax

Change your model to
public class Phasessfilter
{
public string Searchterm {get;set;}
public string ob1 {get;set;}
public string ob2 {get;set;}
public string ob3 {get;set;}
public List<string> ob4 { get; set; }
public List<string> ob5 { get; set; }
public Phasessfilter()
{
ob4 = new List<string>();
ob5 = new List<string>();
}
}

Hey the code written is absolutely fine you just need to test with the values in it and it works just fine.
here is sample Js code
var searchterm = "test1";
var recr = "test2";
var study = "test3";
var results = "test4";
var phases1 = ["Test5","Test6"];
var fund = ["Test6", "Test7"];
debugger;
var values = { Searchterm: searchterm, ob1: recr, ob2: study, ob3: results, ob4: phases1, ob5: fund }
$.post(path + "/Dashboard/Home/GtRlts", values, function (abc) {
});
and the output for a reference rest of the code is same.

You have just define array variable so it get null value
var phases1 = [];
var fund = [];
You have to add items in it:
var phases1 = [1,2];
var fund = [3,4];

Related

How to POST javascript object, javascript object list and file list to asp.net core controller

I want to pass all data to controller after clicking button.
var data = new FormData();
Here is my javascript object
var info = {};
info.CorporateName = $("input[name*='CorporateName']").val();
info.CorporatePhone1 = $("input[name*='CorporatePhone1']").val();
info.CorporatePhone2 = $("input[name*='CorporatePhone2']").val();
info.CorporateEmail = $("input[name*='CorporateEmail']").val();
I can reach these datas from the controller with code below
$.each(info, function (key, input) {
data.append(key, input);
});
Here is my file list. I can reach these files from the controller with code below
var allfiles = $(".required-files");
for (var i = 0; i < allfiles.length; i++)
{
var files = allfiles[i].files;
data.append('files', files[0]);
}
Here is my packages cookie. I can't reach package list from the controller
var packageList = $.parseJSON($.cookie("packageList"));
data.append('packageList',JSON.stringify(packageList));
I can post files, my info object but I can't post cookie list
Here is my controller
[HttpPost]
public async Task<IActionResult> create(IEnumerable<IFormFile> files, List<PostServiceDto> packageList, ModelDto Model)
{
// files = not null, Model not null, but packageList = null
var model = Request.Form;
return View();
}
My package model
public class PostServiceDto
{
public string Type { get; set; }
public string Name { get; set; }
public string Price { get; set; }
public string Id { get; set; }
public string Count { get; set; }
}
I couln't take the list it with parameter but I solved it getting json object form request body.
the value returned from request ={\"Type\":\"3\",\"Name\":\"dfsfsdfs\",\"Price\":\"44,00\",\"Id\":\"2\",\"Count\":1},{\"Type\":\"3\",\"Name\":\"Yeni Paket\",\"Price\":\"49,90\",\"Id\":\"1\",\"Count\":1}
Solution
foreach (var item in Request.Form.Keys)
{
if(item == "packageList")
{
clearObject(Request.Form[item]);
}
}
public List<PostServiceDto> clearObject(string value)
{
List<PostServiceDto> postServices = new List<PostServiceDto>();
List<PostServiceDto> myDeserializedObjList =
(List<PostServiceDto>)Newtonsoft.Json.JsonConvert.DeserializeObject(value, typeof(List<PostServiceDto>));
return myDeserializedObjList;
}
code source : [https://www.codeproject.com/Tips/79435/Deserialize-JSON-with-C]

How to update my data table with POST values. ASP.NET

I want to update values ​​in my database. to make sure my script was working and to send the values ​​I created a POST method to check and the values ​​are coming.
My question now is with the values ​​coming to the method, how to update or save my values ​​in the database?
Controller:
[HttpPost]
public JsonResult EditPost(Programa_Cor_Info_Status statusData)
{
Programa_Cor_Info_Status status = new Programa_Cor_Info_Status
{
ID_Info = statusData.ID_Info,
Status = statusData.Status,
Obs = statusData.Obs,
};
return Json(status, JsonRequestBehavior.AllowGet);
}
I tried using db.savechanges on my controller but to no avail.
Could someone help me with an example?
Thanks
------------Update-----------------------------------------
[HttpPost]
public ActionResult EditPost(Programa_Cor_Info_Status statusData, int ID_Status)
{
Programa_Cor_Info_Status status = new Programa_Cor_Info_Status
{
ID_Info = statusData.ID_Info,
Status = statusData.Status,
Obs = statusData.Obs,
};
var q = db.Programa_Cor_Info_Status.Where(m => m.ID_Info == ID_Status).FirstOrDefault();
q.ID_Info = ID_Status;
db.Entry(q).State = EntityState.Modified;
db.SaveChanges();
return Json(status, JsonRequestBehavior.AllowGet);
}
namespace Balu0._1.Models
{
using System;
using System.Collections.Generic;
public partial class Programa_Cor_Info_Status
{
public int ID_Info { get; set; }
public int ID_Programa { get; set; }
public int ID_Linha_Cor { get; set; }
public string Status { get; set; }
public string Obs { get; set; }
}
}
If you stll don't have, in your view add hidden model field with ID_Info value.
Change your action to this:
public ActionResult EditPost(Programa_Cor_Info_Status statusData)
{
var existItem = db.Programa_Cor_Info_Status.Find(statusData.ID_Info);
// or if you dont have a proper primary key you can try
var existItem = db.Programa_Cor_Info_Status
.Where( i=> i.ID_Info== statusData.ID_Info).FirstOrDefault();
if (existItem != null)
{
db.Entry(existItem).CurrentValues.SetValues(statusData);
var result = db.SaveChanges(); // if result==0 then error
} else ...error
return Json(statusData, JsonRequestBehavior.AllowGet);
}
thanks for the help i already got !!!
db.Entry(status).State = EntityState.Modified;
db.SaveChanges();
return Json(status, JsonRequestBehavior.AllowGet);

Why is Razor DropDownListFor bound with array element not initializing? [duplicate]

I'm developing an ASP.NET MVC 5 application, with C# and .NET Framework 4.6.1.
I have this View:
#model MyProject.Web.API.Models.AggregationLevelConfViewModel
[...]
#Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, (SelectList)Model.HelperCodeTypeItems, new { id = "Configurations[0].HelperCodeType" })
The ViewModel is:
public class AggregationLevelConfViewModel
{
private readonly List<GenericIdNameType> codeTypes;
private readonly List<GenericIdNameType> helperCodeTypes;
public IEnumerable<SelectListItem> CodeTypeItems
{
get { return new SelectList(codeTypes, "Id", "Name"); }
}
public IEnumerable<SelectListItem> HelperCodeTypeItems
{
get { return new SelectList(helperCodeTypes, "Id", "Name"); }
}
public int ProductionOrderId { get; set; }
public string ProductionOrderName { get; set; }
public IList<Models.AggregationLevelConfiguration> Configurations { get; set; }
public AggregationLevelConfViewModel()
{
// Load CodeTypes to show it as a DropDownList
byte[] values = (byte[])Enum.GetValues(typeof(CodeTypes));
codeTypes = new List<GenericIdNameType>();
helperCodeTypes = new List<GenericIdNameType>();
for (int i = 0; i < values.Length; i++)
{
GenericIdNameType cType = new GenericIdNameType()
{
Id = values[i].ToString(),
Name = EnumHelper.GetDescription((CodeTypes)values[i])
};
if (((CodeTypes)values[i]) != CodeTypes.NotUsed)
codeTypes.Add(cType);
helperCodeTypes.Add(cType);
}
}
}
And Models.AggregationLevelConfiguration is:
public class AggregationLevelConfiguration
{
public byte AggregationLevelConfigurationId { get; set; }
public int ProductionOrderId { get; set; }
public string Name { get; set; }
public byte CodeType { get; set; }
public byte HelperCodeType { get; set; }
public int PkgRatio { get; set; }
public int RemainingCodes { get; set; }
}
I need to set selected value in these properties:
public IEnumerable<SelectListItem> CodeTypeItems
{
get { return new SelectList(codeTypes, "Id", "Name"); }
}
public IEnumerable<SelectListItem> HelperCodeTypeItems
{
get { return new SelectList(helperCodeTypes, "Id", "Name"); }
}
But I can't set it in new SelectList(codeTypes, "Id", "Name"); or new SelectList(helperCodeTypes, "Id", "Name"); because the selected value are in Configurations array: fields AggregationLevelConfiguration.CodeType and AggregationLevelConfiguration.HelperCodeType.
I think I have to set selected value in the View, but I don't know how to do it.
How can I set the selected values?
Unfortunately #Html.DropDownListFor() behaves a little differently than other helpers when rendering controls in a loop. This has been previously reported as an issue on CodePlex (not sure if its a bug or just a limitation)
The are 2 option to solve this to ensure the correct option is selected based on the model property
Option 1 (using an EditorTemplate)
Create a custom EditorTemplate for the type in the collection. Create a partial in /Views/Shared/EditorTemplates/AggregationLevelConfiguration.cshtml (note the name must match the name of the type
#model yourAssembly.AggregationLevelConfiguration
#Html.DropDownListFor(m => m.HelperCodeType, (SelectList)ViewData["CodeTypeItems"])
.... // other properties of AggregationLevelConfiguration
and then in the main view, pass the SelectList to the EditorTemplate as additionalViewData
#using (Html.BeginForm())
{
...
#Html.EditorFor(m => m.Configurations , new { CodeTypeItems = Model.CodeTypeItems })
...
Option 2 (generate a new SelectList in each iteration and set the selectedValue)
In this option your property CodeTypeItems should to be IEnumerable<GenericIdNameType>, not a SelectList (or just make codeTypes a public property). Then in the main view
#Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, new SelectList(Model.CodeTypeItems, "Id", "Name", Model.Configurations[0].HelperCodeType)
Side note: there is no need to use new { id = "Configurations[0].HelperCodeType" - the DropDownListFor() method already generated that id attribute
I wrote this class to overcome an issue I was having with selecting an option in an html select list. I hope it helps someone.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Login_page.Models
{
public class HTMLSelect
{
public string id { get; set; }
public IEnumerable<string> #class { get; set; }
public string name { get; set; }
public Boolean required { get; set; }
public string size { get; set; }
public IEnumerable<SelectOption> SelectOptions { get; set; }
public HTMLSelect(IEnumerable<SelectOption> options)
{
}
public HTMLSelect(string id, string name)
{
this.id = id;
this.name = name;
}
public HTMLSelect(string id, string name, bool required, IEnumerable<SelectOption> options)
{
this.id = id;
this.name = name;
this.required = required;
}
private string BuildOpeningTag()
{
StringBuilder text = new StringBuilder();
text.Append("<select");
text.Append(this.id != null ? " id=" + '"' + this.id + '"' : "");
text.Append(this.name != null ? " name=" + '"' + this.name + '"' : "");
text.Append(">");
return text.ToString();
}
public string GenerateSelect(IEnumerable<SelectOption> options)
{
StringBuilder selectElement = new StringBuilder();
selectElement.Append(this.BuildOpeningTag());
foreach (SelectOption option in options)
{
StringBuilder text = new StringBuilder();
text.Append("\t");
text.Append("<option value=" + '"' + option.Value + '"');
text.Append(option.Selected != false ? " selected=" + '"' + "selected" + '"' + ">" : ">");
text.Append(option.Text);
text.Append("</option>");
selectElement.Append(text.ToString());
}
selectElement.Append("</select");
return selectElement.ToString();
}
}
public class SelectOption
{
public string Text { get; set; }
public Boolean Selected { get; set; }
public string Value { get; set; }
}
}
And
public IEnumerable<SelectOption> getOrderTypes()
{
List<SelectOption> orderTypes = new List<SelectOption>();
if (this.orderType == "OptionText")
{
orderTypes.Add(new SelectOption() { Value = "1", Text = "OptionText", Selected = true });
} else
{
orderTypes.Add(new SelectOption() { Value = "2", Text = "OptionText2" });
}
}
And to use it:
#{
Login_page.Models.HTMLSelect selectElement = new Login_page.Models.HTMLSelect("order-types", "order-types");
}
#Html.Raw(selectElement.GenerateSelect(Model.getOrderTypes()));
I leave this in case it helps someone else. I had a very similar problem and none of the answers helped.
We had in a view this line at the top:
IEnumerable<SelectListItem> exitFromTrustDeed = (ViewData["ExitFromTrustDeed"] as IEnumerable<string>).Select(e => new SelectListItem() {
Value = e,
Text = e,
Selected = Model.ExitFromTrustDeed == e
});
and then below in the view:
#Html.DropDownListFor(m => m.ExitFromTrustDeed, exitFromTrustDeed, new { #class = "form-control" })
We had a property in my ViewData with the same name as the selector for the lambda expression and for some reason that makes the dropdown to be rendered without any option selected.
We changed the name in ViewData to ViewData["ExitFromTrustDeed2"] and that made it work as expected.
Weird though.

How to move to other action method on button click in MVC

I made a form where user can enter all details. Like a fill up form. After filling up form. When user click on Save button it should be automatically move to other action method in same controller. And must show data in GRID VIEW in MVC. Where in grid view user can update and save all data which he entered while filling up the form.
I used DB first approach. And make a view model class. Here is the code of View Model class.
public class ViewModel
{
[Required(ErrorMessage = "Please Enter Prodcut Name")]
[DisplayName("Product Name")]
public string Product_Name { get; set; }
[Required(ErrorMessage = "Please Choose Category")]
public int SelectedValue { get; set; }
[Required(ErrorMessage = "Enter Price")]
[DisplayName("Enter Price")]
public decimal Price { get; set; }
[Required(ErrorMessage = "Choose Picture")]
[DisplayName("Choose Picture")]
public string Picture { get; set; }
[Required(ErrorMessage = "Choos Country")]
public Nullable<int> Country_ID { get; set; }
[Required(ErrorMessage = "Choose Type")]
[DisplayName("Choose Product Type")]
public string Product_Type { get; set; }
public SelectList CategoryList { get; set; }
public SelectList CountryList { get; set; }
[Required(ErrorMessage = "Select Date")]
public DateTime Date { get; set; }
}
Controller Code
ProductionEntities DBContext = new ProductionEntities();
public ActionResult Index()
{
ViewModel model = new ViewModel();
List<tblCategory> CategoryList = DBContext.tblCategories.ToList();
model.CategoryList = new SelectList(CategoryList, "Category_ID", "Category_Name");
List<tblCountry> CountryList = DBContext.tblCountries.ToList();
model.CountryList = new SelectList(CountryList, "Country_ID", "Country_Name");
return View(model);
}
[HttpPost]
public ActionResult Index(ViewModel model)
{
//ViewModel v = new ViewModel();
//if (image1!=null)
//{
// model.Picture = new byte[image1.ContentLength];
// image1.InputStream.Read(model.Picture, 0, image1.ContentLength);
//}
List<tblCategory> CategoryList = DBContext.tblCategories.ToList();
model.CategoryList = new SelectList(CategoryList, "Category_ID", "Category_Name");
List<tblCountry> CountryList = DBContext.tblCountries.ToList();
model.CountryList = new SelectList(CountryList, "Country_ID", "Country_Name");
if (!ModelState.IsValid)
{
tblProduct product = new tblProduct();
product.Category_ID = model.SelectedValue;
product.Country_ID = model.Country_ID;
product.Price = model.Price;
product.Product_Name = model.Product_Name;
product.Date = model.Date;
product.Picture = model.Picture;
product.Product_Type = model.Product_Type;
try
{
DBContext.tblProducts.Add(product);
DBContext.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
System.Console.WriteLine("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
}
}
}
}
return View(model);
}
You should follow P-R-G (Post-Redirect-Get) pattern. After successfully saving the record, send a redirect response to the browser which will issue a totally new GET request to the action method which renders the tabular data.
DBContext.tblProducts.Add(product);
DBContext.SaveChanges();
return RedirectToAction("List");
and in your List action method you will read the records needed for the tabular data and render it in it's view.

Why "System.IndexOutOfRangeException" occurs for string in ajax using ASP.Net?

Actually my ajax code is working perfectly if I remove that one particular string variable
I am calling ajax, then server will pick some data from SQL Server and store it into string variable. Every variable returning perfectly except that one variable. When I check console, it return exception "System.IndexOutOfRangeException"
Here is my ajax code
$('.list-of-link').on('click', 'a', function (e) {
e.preventDefault();// add this line
alert($(this).html());
//window.location.replace("ReportTotalSalesPivot.aspx");
var userFileName = $(this).html();
$.ajax({
url: 'SavedReports.aspx/getReportDetails',
method: 'post',
contentType: 'application/json',
data: '{userFileName:"' + userFileName + '"}',
dataType:'json',
success: function (data) {
alert('success : ReportData = ' + data.d.ReportData);
},
error: function (error) {
alert('Please Call Administrator');
}
})
})
WebMethod code
[WebMethod]
public static SavedReport getReportDetails(string userFileName)
{
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select ReportData,ReportFilter,FromDate,ToDate,SelectedData,SelectedCoulmn,SelectedRow,HiddenTableRecord ToDate FROM [HQWebMatajer].[dbo].[ReportSave] where UserID=#UserID and UserFileName=#UserFileName";
cmd.Parameters.AddWithValue("#UserID", UserID);
cmd.Parameters.AddWithValue("#UserFileName", userFileName);
con.Open();
SavedReport savedReport = new SavedReport();
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
byte[] binaryString = (byte[])rd["ReportData"];
savedReport.ReportData = Encoding.UTF8.GetString(binaryString);
savedReport.ReportFilter = rd["ReportFilter"].ToString();
savedReport.FromDate = rd["FromDate"].ToString();
savedReport.ToDate = rd["ToDate"].ToString();
savedReport.SelectedData = rd["SelectedData"].ToString();
savedReport.SelectedColumn = rd["SelectedCoulmn"].ToString();
savedReport.SelectedRow = rd["SelectedRow"].ToString();
savedReport.HiddenTableRecord = rd["HiddenTableRecord"].ToString();
}
return savedReport;
}
}
Error occur in the last variable HiddenTableRecord
The following record is actual record for HiddenTableRecord from SQL Server tq.StoreID$$$ IN('1001')$$$
SavedReport class code
public class SavedReport
{
public string UserID { get; set; }
public string ReportName { get; set; }
public string UserFileName { get; set; }
public string ReportData { get; set; }
public string ReportFilter { get; set; }
public string FromDate { get; set; }
public string ToDate { get; set; }
public string SelectedData { get; set; }
public string SelectedColumn { get; set; }
public string SelectedRow { get; set; }
public string HiddenTableRecord { get; set; }
}
Error msg
{Message: "HiddenTableRecord",…}
ExceptionType:"System.IndexOutOfRangeException"
Message:"HiddenTableRecord"
Note
If I comment this line savedReport.HiddenTableRecord = rd["HiddenTableRecord"].ToString();. Error is not occurring and it returns all the records what I expect
The problem comes because your SqlDataReader doesn't contains "HiddenTableRecord"
Maybe there is an issue in your SqlRequest (a comma is missing in your example between HiddenTableRecord and ToDate):
"select ReportData,ReportFilter,FromDate,ToDate,SelectedData,SelectedCoulmn,SelectedRow,HiddenTableRecord , ToDate FROM [HQWebMatajer].[dbo].[ReportSave] where UserID=#UserID and UserFileName=#UserFileName";

Categories