How to pass list values from an Action method to another in the same controller? - asp.net-mvc-4

How to pass data from a method to another inside a controller and display.
The first method have list of values and this has to pass to the another and display that data from the view
first action method:
[HttpPost]
public ActionResult matchpin(string id)
{
int d = Convert.ToInt32(id);
List<pin> plist = new List<pin>();
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("getpin", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#pin", d);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
var pin = new pin()
{
// Vid=Convert.ToInt32(reader["Vid"]),
po = Convert.ToString(reader["po"]),
};
plist.Add(pin);
}
}
}
return RedirectToAction("Index","home",new{ s =plist});
}
second action method:
public ActionResult Index(List<pin> plist)
{
// return View();
ViewBag.s = plist;
return View("Index");
//return new ContentResult { Content =TempData["Data"].ToString() };
}

redirect in the first action method has to be
return RedirectToAction("Index","home",new{plist});
instead of
return RedirectToAction("Index","home",new{s=plist});
because ASP MVC framework match it by method parameter name so you have to pass it with the same name in the action method two which is plist.

Using action you can pass limited data.
Mvc provides tempdata to pass data from one action to another.
You can also using session for storing data.
e. g
For passing data:
TempData["mydata"] =myList;
For data retrieval :
var data=TempData["mydata"] ;
Hope that clarify you question.

Using action you can pass limited data.
Mvc provides TempData to pass data from one action to another.
You can also using session for storing data.
e.g
For storing data:
TempData["mydata"]=data;
For retrieving :
var storedData=TempData["mydata"]

You can use TempData: first store your value in TempData, and then redirectToAction:
TempData.MyList=plist;
return RedirectToAction("Index","home");

Related

Trying to update a row value in SQL with ASP.NET Core 6

I am trying to update a row value in SQL with my DbContext in ASP.NET Core 6. The column is named TextField but I get this error:
InvalidOperationException: The instance of entity type 'TextField' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
Here is my code:
[HttpPost]
public IActionResult UploadText(string newText, string section)
{
MgvaKrantransportContext DBContext = new MgvaKrantransportContext();
var textSelection = DBContext.TextFields.Where(m => m.Section.Equals(section)).ToList();
TextField newTextField = new TextField();
foreach (var textField in textSelection)
{
newTextField = new TextField() { Id = textField.Id, Section = section, TextContent = newText };
}
DBContext.Entry(newTextField).Property(x => x.TextContent).IsModified = true;
DBContext.SaveChanges();
return RedirectToAction("Index");
}
Thanks in advance
Best regards Max
If you want to update using a stub entity, don't query the database first. Simply remove this line
var textSelection = DBContext.TextFields.Where(m => m.Section.Equals(section)).ToList();
Alternatively, update the returned TextField(s) and don't create a new one.
eg
foreach (var textField in textSelection)
{
textField.TextContent = newText ;
}
DBContext.SaveChanges();

How to add data and remove same data from other table in asp.net core?

I am trying to remove the same row from the existing table PendingTestResult which is added in TestResult table. but it's not working kindly help me out to resolve this
this is controller
[HttpPost]
[Route("Reception/PatientTests/SaveTestResult")]
public async Task<IActionResult> SaveTestResult(List<TestResult> testResults)
{
if (ModelState.IsValid)
{
foreach (TestResult tr in testResults)
{
_db.Add(tr);
await _db.SaveChangesAsync();
var TestResultId = new PendingTestResult { Id = tr.Id };
_db.Remove<PendingTestResult>(TestResultId);
await _db.SaveChangesAsync();
}
// return new JsonResult("Index");
}
return new JsonResult(testResults); ;
}
here i want to remove same rows from PendingTestResult table which is newly added in TestResult Table.
please make sure the data you want to delete is available in the table.
instead of creating a new object, I would recommend using the Find method
assuming _db is the object of DbContext.
_db.Add(tr);
_db.PendingTestResults.Remove(_db.PendingTestResults.Find(tr.Id));
await _db.SaveChangesAsync();
please change the DbSet property name.
If you want to debug your code, use sql server profiler.

Pass Generic Object Dynamically

I am trying to dynamically show a table depending on what tableName user has selected from dropdown. I am passing a json object from my web Controller(.Net Core) so in order to do it, I am first converting my dataTable to list of objects using function
public static List<T> ConvertTableToList<T>(this DataTable table) where T : class, new()
{
try
{
List<T> list = new List<T>();
foreach (var row in table.AsEnumerable())
{
T obj = new T();
foreach (var prop in obj.GetType().GetProperties())
{
try
{
PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
}
catch(Exception ex)
{
throw ex;
}
}
list.Add(obj);
}
return list;
}
catch
{
return null;
}
}
and call this function in my Get Request
public IActionResult GetTableDetailsByTableName(string TableNameSelected)
{
//To get the data for the Table Selected
DataTable TableDetails = ReferenceTableLogics.getTableDetails(TableNameSelected);
var TableDetailsInList = ConverterClass.ConvertTableToList<CSBM_AGE_BAND>(TableDetails);
return Ok(TableDetailsInList);
}
Now the issue is that I need to tell my class Name (eg CSBM_AGE_BAND in this case) depending on what user has selected in dropdown (TableNameSelected).
Is there any way by which I can dynamically pass this class name to my function ConvertTableToList ?
Using reflection you can invoke your generic extension method:
Type genericType = Type.GetType("YourNamespace.ConverterClass");
MethodInfo methodInfo = typeof(ConverterClass).GetMethod("ConvertTableToList", BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(genericType);
var TableDetailsInList = methodInfo.Invoke(null, new object[]{ TableDetails });

I want to select different packages on the basis of states, how to get value

public ActionResult Rajasthan()
{
//List<PackageGallery> all = new List<PackageGallery>();
using (travelAndTourismEntities objentity = new travelAndTourismEntities())
{
List<PackageGallery> all = (from p in objentity.PackageGalleries where p.ParentCategory == "Rajasthan" orderby p.Imageid select p).ToList();
// all = objentity.PackageGalleries.ToList();
return View(all);
}
}
I am writing this query but this is specific to rajasthan only how to make it generalize
You can create a parameter to your action method where you accept the state name you want to use in your filter.
public ActionResult PackageGalleries(string id)
{
var all = new List<PackageGallery>();
using (var db = new travelAndTourismEntities())
{
all = db.PackageGalleries
.Where(s=>s.ParentCategory==id)
.OrderBy(x=>x.ImageId).ToList();
}
return View(all);
}
And you can call it like yourSiteName/yourControllerName/PackageGalleries/rajasthan or yourSiteName/yourControllerName/PackageGalleries/kerala
The last part of the url will be mapped to the id parameter of the action method.

Loop through datatable to create json in web api

I am trying to create a JSON response from the WebServices that return a dataset. How can I loop through the datatable and put those values in client model? When I try to loop through the datatable I get invalid initiater error.
Here is my code:
public class ClientsController : ApiController
{
public IEnumerable<ClientResponseModels> GetAllClients()
{
//retrieves list of all the clients
var dsClients = ClientRepository.GetAllClients();
//create a json response object
ClientResponseModels[] response = new ClientResponseModels[]
{
new ClientResponseModels
{
UserId= userDetails.UserID,
UserName=userDetails.LoginName,
LocationName=centreLocation.ToString(),
Clients = new List<ClientModels>
{
foreach(DataRow row in dsClients.Tables[0].rows)
{
new ClientModels //these values need to come from datatable
{
Id =Convert.ToInt32(row["client_id"]),
ClientName=Convert.ToString(row["client_nme"])",
DOB= Convert.ToDateTime(row["birth_date]")
}
}
}
}
};
return response;
}
else {
throw new HttpResponseException(HttpStatusCode.Forbidden);
}
}
I you use entity framework change datacontext configuration.
MyDataContext db = new MyDataContext();
db.Configuration.LazyLoadingEnabled = false;
db.Configuration.ProxyCreationEnabled = false;
I think the function is the cause as your code I'd looping through a queryable. You can retrieve the data first before looping e.g. GetAllClients().ToList()