passing a session variable in link created by for loop C# - c#

I have a page reading an api thats giving a list of ID's.
I then want that to create a link that then sends that ID to another API to get that individual object.
I've got the pages working manually but now trying to send the data between them is the issue.
My current code is this
#{
for (var i = 0; i < Model.records.Count; i++)
{
string currID = Model.records[i].ID;
<td>#Html.ActionLink(Model.records[i].ID, "Game", "Home", Session["game"] = currID)</td>
<td>#Model.records[i].GameName</td>
<td>#Model.records[i].Player1</td>
<td>#Model.records[i].Player2</td>
<td></td><br />
}
}
What this does, And I understand Why, is pass the final record's ID to the api, and always gives me that result, as i is the final value at that point.
how can I tell the link that it needs to keep it's iteration of i and pass that value?

With this expression,
Session["game"] = currID
You are actually updating the Session item value within the loop for each iteration with the current value of currID.
If you want to send the Session item value as querysting/route values, you may use the overload which takes 5 params. The fourth parameter is an anonymous object where you will specify the key and values, these key and values will be used to generate the URL.
For example, the below code will add the gameId querystring item and it's value will be the value stored in Session["game"]
#{
var game = Session["game"];
for (var i = 0; i < Model.records.Count; i++)
{
string currID = Model.records[i].ID;
<td>#Html.ActionLink(Model.records[i].ID, "Game", "Home",
new { gameId = game }, null)</td>
<td>#Model.records[i].GameName</td>
}
}
Assuming your Game action method has a parameter with name gameId
public ActionResult Game(string gameId)
{
// to do : Return something
}
If you want to send the currID as well, pass that too
#Html.ActionLink(Model.records[i].ID, "Game", "Home",
new { gameId = game, currId = currID }, null)
The fifth parameter( where I passed null) is for htmlAttributes which will be used to add other HTML attributes to the element rendered by this helper (Ex : If you want to add a CSS classs etc)

Related

How to pass query parameter value into HTML.Partial model?

I have an MVC page (Not .Net Core) which contains the below code
#Html.Partial("~/Views/ProductLanding/product.cshtml", Model.Product(1))
The query in the address bar is similar to ..../products/product?id=4
How could i pass in the query value of 4 (or whatever it might be) into the Model.Product(ID) which then calls some code in my database to retrieve that product?
Using a hardcoded value works so im not sure if i should be doing this differently or if there is a better approach?
Finally hopefully this wont make a difference but once i have this working i would like to change the URL to something more friendly i.e. ..../products/product/4
method 1 : get route data in razor view
{
var id = Context.GetRouteData().Values["id"];
}
#Html.Partial("~/Views/ProductLanding/product.cshtml", Model.Product(id))
method 2 : pass id with controller (viewbag or model)
public ActionResult Product(int id){
var model= {
...
Id = id
}
//ViewBag.Id = id;
return View(model)
}
view:
#model ViewModel
{
var id = int.Parse(ViewBag.Id); // alternative sln.
}
#Html.Partial("~/Views/ProductLanding/product.cshtml", Model.Product(Model.Id))
I have been using the below method and it works for me you can also try this
#Html.Action(, , new { #<Parameter_name> = })
Eg:
#Html.Action("DetailsProducts", "CREDITNOTEs", new { #id = Model.ID })

session's variables values retrieving in _LayoutPartial in asp.net mvc

I'm filling values to a session's like following to retrive those in _LayoutPartial view
if (userdata != null)
{
Session["userdata"] = new SampleViewModel { FirstName = userdata.UserFirstName, LastName = userdata.UserLastName };
FormsAuthentication.SetAuthCookie(loginmodel.UserName, false);
return RedirectToAction("Dashboard", "Home", new { username = loginmodel.UserName });
}
I want to retrive those values in _LayoutPartial View , So I tried somethin like following
<a class="sa">
(#Session["userdata"] as ProjectName.Models.SampleViewModel).FirstName
(#Session["userdata"] as ProjectName.Models.SampleViewModel).LastName
</a>
But this is not retrieving data properly . In this _LoginPartial I'm not Referencing any model also
You have your parenthesis in the wrong spot, and you need a double set - one for the casting (inner set) and one for the razor execution (outer set). It needs to be
#((Session["userdata"] as ProjectName.Models.SampleViewModel).Name)

How do you Request[""] with a Dynamic Variable? Request["#Variable"]?

I'm building a form, where the number of questions, or inputs on the form varies depending on the value in a database.Each input on the form is a radio type. The name of the tags are dynamic and are loaded from the database using #db.row.questionID which would look something like: <span name=#id> and equal a value of 1 through whatever queries were requested.
My issue is, i wrote the form using post, and i want to submit the values back into a separate database, but i dont know how to request multiple values, that changes dynamically based on query.
Sample code i wrote, it doesnt give me any errors, but it doesnt give me any results either.
foreach(var prow in poll){
var Question = prow.PollId;
if (Request.Form["#prow.PollId"] == "A") {
int AnsA = row.ResultsA;
AnsA = AnsA + 1;
db.Execute("UPDATE Results SET ResultsA=#0 WHERE ResultsId=#1", AnsA, Question);
}
i have also tried:
if (Request["prow.PollId"] == "B") {
int AnsB = row.ResultsB;
AnsB += 1;
db.Execute("UPDATE Results SET ResultsB=#0 WHERE ResultsId=#1", AnsB, prow.PollId);
}
Do you want to get value in form with dynamic inputs? If yes, you can try this:
NameValueCollection nvc = Request.Form;
foreach (var item in Request.Form.AllKeys)
{
//do something you want.
// Examble : if(item == "A")// item will return name of input
// Note: nvc[item] return value of input
}
Update:
Request.Form.AllKeys will return all of input name in form.
We use foreach to lopp through colections of input name.
Use nvc[item] or Request.Form[item] to get value of input.
You can read this article :c#: get values posted from a form

RavenDb - Write query and select item where it's propertyName equals a string

Is it possible to write a query and select an item where its propertyName equals a string?
I want to pass in a string to a method, where my string holds the value of a propertyName. And then use it in a query to select my property that equals that string. Is this possible?
I know I'm not writing any code here, just asking if this is possible to do.
EDIT:
Ok this as my solution a come up wth so far, and I know, it's far from a good solution. But I will put here and if you can give me a better solution, feel free to do it. Any help is a appreciated!
This is one of the Raven-document I could work with:
{
"WelcomeHeader": "header",
"WelcomeText": "some text",
"Template": {
"Id": "RouteConfigTemplates/1",
"Name": "Index",
"Controller": "Home",
"Action": "Index",
"View": "Index",
"ContentPageType": "Core_StudioL.Models.IndexCorePage, Core_StudioL"
},
"Url": "/"
"Title": "Start"
}
Im my view a have a couple of WYSIWYG-editors, and each time I push the save button on one of my editors i sending the parameters to this mvc-controller-method below:
string model : is my whole model in json-format as string.
string activeId : is the id of the passed WYSIWYG-editors div (activeId = The sent propertys propertyName)
string contentToUpdate : is the value I want to update
[ValidateInput(false)]
public JsonResult SaveContent(string model, string activeId, string contentToUpdate)
{
//parse model to json
var modelAsJson = JObject.Parse(model);
//if the property-name == item.key, replace it
foreach (var item in modelAsJson)
{
if (item.Key == activeId)
{
item.Value.Replace(contentToUpdate);
}
}
//find the right contentPageType
string cType = modelAsJson["Template"]["ContentPageType"].ToString();
//convert back to string
string newModel = modelAsJson.ToString(Formatting.None);
//here I need to have many if-statments (not an optimal solution) to pick out the right contentPageType, here is a example of one of them.
//The problem here
if (cType.Equals("Core_StudioL.Models.IndexCorePage, Core_StudioL"))
{
var jsonSerializer = new JavaScriptSerializer();
var modelAsCorrectModel = jsonSerializer.Deserialize<IndexCorePage>(newModel);
//Here I'm having problem to update a single value, because the values sent in to the controller could be any..
//So my ugly solution here is to delete the whole document from raven, and then save a new one with the updated values. If a just could only save the `string contentToUpdate`
//
var page = RavenSession.Load<CorePage>(modelAsCorrectModel.Id);
RavenSession.Delete(page);
RavenSession.SaveChanges();
RavenSession.Store(modelAsCorrectModel);
RavenSession.SaveChanges();
var modelToReturn = new JavaScriptSerializer().Serialize(modelAsCorrectModel);
return Json(modelToReturn);
}
return null;
}
by doing it this way, my model in the razor-view never gets updated before I reload the page.
That means: If a save on of my WYSIWYG-editors, it's content gets updated to ravendb.
But if I save another one without refreshing the page after I saved the first one.
Then just that another one gets updated. Because the model sent in to the save-method is still the first model sent in to the view.
So: the first one saved, then gets overwritten by the original Model, because it still holds the original models values!

Object does not contain a definition for Title

I have a controller that passes data to my view through the ViewBag
My controller:
var aJobs = from a in gdb.AcceptedJobs
where a.Job.EmployerID == (Guid)Session["UserID"] && !a.Archived
select new { a.Job.Title, a.Job.Address };
ViewBag.jobs = aJobs;
return View("Employer");
My view:
foreach (var job in ViewBag.jobs)
{
#job.Title
#job.Address
}
Now, when i browse to the page i get error object does not contain a definition for Title, at #job.Title, why is this?
I'm using ASP.Net MVC3 C#
Try creating your anonymous type this way
select new { Title = a.Job.Title, Address = a.Job.Address };
When im debugging, and the error is thrown i checked the locals. Then i can clearly see that in the first iteration, the job-object contains a Title-string with the value of my name.

Categories

Resources