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

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.

Related

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);

Passing complex javascript object to controller. List of objects are always 0

I have a object that I am trying to pass to my C# controller. All the properties get populated except the list I have is always count =0. I have tried setting the header to content-type/json and Json.stringify. Also for testing I am returning the product list from another call so I know that returns a list of products to my view that is formatted correctly.
example for creating request
var request =
'Id':null,
...
... rest of data is here standard properites
...
'Products':productlist
for product list I am currently using the return value from a call that returns a List
return $http.post('api/Enty/Save', request )
.error(function (data, status, headers, config) {
errorLog('error: ' + data);
});
public class Person:IPerson
{
[Required]
public int Id { get; set; }
[MaxLength(90)]
public String Address1 { get; set; }
[MaxLength(90)]
public String Address2 { get; set; }
[MaxLength(40)]
public String Address3 { get; set; }
[MaxLength(40)]
public String City { get; set; }
[MaxLength(2)]
public String State { get; set; }
[MaxLength(40)]
public String Province { get; set; }
[MaxLength(10)]
public String Zip { get; set; }
public IList<IProduct> Products { get; set; }
}
[HttpPost()]
public Response Save(person r)
{}
UPDATE
If I make it List instead of IList it works. Any ideas why?
Turns out the issue was not the Ilist but the Iproduct. I just changed to a concrete class for that property

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.

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";

JavaScript function does not fire when using child model data

I am working on displaying data in a separate div and when I pass my javascript function data it does not fire onclick. It works when I use data from the parent but not after I cast the data from the parent into a child and try to pass the JS function with that data.
##view##
#using WebApplication2.Models
#model IEnumerable<WebApplication2.Models.OBJECT>
#{
ViewBag.Title = "CompAndMon";
}
<script>
//this function does not fire when called
function setO(OfficeLocation,Name,Email,Phone,NumComputers,NumMonitors) {
var text = "Primary Contact Name " + Name+"\n Primary Contact Email: " +Email +"\n Primary Contact Phone: " +Phone +"\n Number of Computers: " +NumComputers +"\n Number Of Monitors: " +NumMonitors;
var location = "Office Location: " + OfficeLocation;
document.getElementById("Nametag").innerHTML = location;
return document.getElementById("OCM").innerHTML = text;
}
//this function does not fire when called
function setComputer(lastS) {
var text = "you selected Item No: " + lastS;
return document.getElementById("OCM").innerHTML = text;
}
//this function operates correctly
function setMonitor(id) {
var text = "you selected Item No: " + id;
return document.getElementById("OCM").innerHTML = text;
}
</script>
#foreach (var item in Model)
{
if (#item.Type == 1)
{
var office = item as Office;
var loc = #office.OfficeLocation;
var Name = #office.Name;
var email = #office.Email;
var phone = #office.Phone;
var mons = #office.NumMonitors;
var comps = #office.NumComputers;
<p><a onlick="setO(#loc,#Name,#email,#phone,#comps,#mons)">#office.Name</a></p>
}
else if (#item.Type == 2)
{
var computer = item as Computer;
<p>  <a onclick="setComputer(#computer.LastUser)">#item.Name1</a></p>
}
else
{
var monitor = item as Monitor;
<p>    <a onclick="setMonitor(#item.ID)">#item.Name1</a></p>
}
}
<h2 id="Nametag" style="text-align:center"></h2>
<div id ="OCM"class="row">
Select a computer or monitor and the information about the de will be displayed here.
</div>
and here are the class models that the view uses
##OCM.cs##
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace WebApplication2.Models
{
public abstract class OBJECT
{
public int ID { get; set; }
public int Type { get; set; }
public string Name1 { get; set; }
}
public class Office:OBJECT
{
public string OfficeLocation { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public int NumComputers { get; set; }
public int NumMonitors { get; set; }
}
public class Computer:OBJECT
{
public String LastUser { get; set; }
public String Name { get; set; }
public int NumMonitors { get; set; }
public String TotalHDSpace { get; set; }
public String FreeHDSpace { get; set; }
public int NumUpdates { get; set; }
}
public class Monitor:OBJECT
{
public String Manufacturer { get; set; }
public String ModelID { get; set; }
public String SerialNum { get; set; }
public int HoursON { get; set; }
public String LastTestTime { get; set; }
public String LastTestType { get; set; }
}
}
When I inspect the element chrome it shows that the data is being passed the the function, but it doesn't run so I am not sure what to do. any help would be appreciated
Here shows that the data was passed to the JS functions when I inspect the element
You use string without quote
setComputer('ted') or setComputer(\"ted\") and not setComputer(ted)
this is the same for email and other arguments
I found that I misspelt onclick in the setO() call and needed to pass my razor variables to the javascript function in single quotes.

Categories