mvc RedirectToAction passing a parameter [duplicate] - asp.net-mvc-2

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
RedirectToAction with parameter
I am in controller home, in ActionResult Id which has a list of string name get returned from a method. I want to RedirectToAction (Id2) using that list. In View -> Id2 the ViewData of that list name get is null, doesn;t contain the list of the Itemsn populated. How can I redirect from an actionResult to another view of another actionresult passing parameter?

Use like this
If there are more than one parameters then:
return RedirectToAction("actionname", new { id = "id", name="name" }); // change parameters according to requirement
If you have only id as parameter then:
return RedirectToAction("actionname", new { id = "id" });

RedirectToAction( new RouteValueDictionary(
new{
controller = "mycontroller",
action = "myaction",
id = "MyId"
}
));

Related

How to update only one column value in database using Entity Framework?

I have a table with columns username, password. Data can be updated by admin for the table.
Now I want to add a new column named IsAgree (as a flag), it need to set when user logs in for the first time. But while setting data, it should not affect other column data, I will only send usename and Isagree flag as an object.
flgDetail = { usename:"vis" Isallowed:True }
[Route("api/TermsAndCondition/setflag")]
public IHttpActionResult post(FlagDetails FlagDetail)
{
var user = _context.table.Where(s => s.UserName == flagDetail.UserName);
}
Should I use post or put?
How can I update only one column?
And it should not affect other columns.
you can use either post or put.It's not a problem.You can update it as shown below.
[Route("api/TermsAndCondition/setflag")]
public IHttpActionResult post(FlagDetails flagDetail)
{
var user = _context.table.Where(s => s.UserName == flagDetail.UserName);
user.IsAgree =flagDetail.Isallowed;
_context.SaveChanges()
}

Entity Framework - many to many relationship - add reference with id

I use entity framework and I have many to many relationship between 2 objects.
Lets say class "question" and class "tag", when I create a new question with many tags, I have list of selected tags in viewmodel. I need to create the question so these tags are added to question but I do not want to reload all the tags.
I mean :
foreach(var id in tagUIds)
{Tag tag = gettag(id);
question.tags.add(tag); }
is not very efficient, is there a way to avoid loading the tag and adding the reference just by id of tag?
Thanks
You can create intermediate entity TagToQuestionLink, map it to many-to-many table and use Collection of this entity in question instead of collection of Tags:
public class TagToQuestionLink
{
TagId{get;set;}
QuestionId{get;set;}
}
Then you can use:
foreach(var id in tagUIds)
{
var tagLink = new TagToQuestionLink{QuestionId = question.Id, TagId = id};
question.tags.add(tagLink);
}
Do not forget, that in this solution question.tags should be ICollection<TagToQuestionLink>.

Updating Foreign Key Table in EF4.1 MVC3. Object is null on POST

When i use foreign keys in the entity framework the foreign key object is null when i do a POST. I am using MVC3 and EF 4.1. I have two tables, Product and Product Details. I am exposing them using the HTML helpers in a Razor view. When the GET happens, the product details are shown. But when i do a form Submit and post to the server, the Product Details collection is null. I lose all my changes.
Any ideas what i am doing wrong?
Thanks for your help!
The Code (i shortened it because it is fairly lengthy):
Database:
Table Product
{
int Id
varchar Name
}
Table ProductDetails
{
int id,
int ProductId, <- foreign key SQL 2008 to Product Table
varchar Details
}
View:
#model WebSite.Models.Product
#{
ViewBag.Title = "MyLifeSaverStoreInfo";
}
#Html.TextBoxFor(m => m.Product.Name)
#Html.TextBoxFor(m => m.Product.ProductDetails.FirstOrDefault().Description)
Controller:
public ActionResult EditProduct(int productId)
{
var Product = _productRepository.GetProduct(productId);
return View(product);
}
[HttpPost]
public ActionResult EditProduct(Product model)
{
string name = model.Name; <- this update comes through
string description = model.ProductDetails.FirstorDefault().Description;
}
Thanks
Got it!
Instead of creating the "Product" entity on the POST EditProduct method, i use a Form Collection and then set each product detail according to that form collection and then save. I don't understand why it doesn't work the first way. I am manually updating the foreign reference. Maybe i am missing something?
[HttpPost]
public ActionResult EditProduct(int id, FormCollection formCollection)
{
var model = new MyLSstoreInfoViewModel{
StoreCurrent = _profileRepository.GetProduct(Id)
};
var productDetails = model.Product.ProductDetails.Where(p => p.productId == id).Single();
productDetaisl.Details = formCollection["details"];
if (TryUpdateModel(model.StoreCurrent))
{
_profileRepository.Save();
}
}
It's a bit late, but maybe useful for someone in the future:
If you pass the primary key of the referenced child as a hidden input in the view, it will correctly resolve the child model in the action.

access to article by article name in ASP.NET MVC2

Greetings. How can I make access to my article or post by their name?
For example: Like at stackoverflow has access to this question by the name
access to article by article name in ASP.NET MVC2access-to-article-by-article-name-in-asp-net-mvc2
On StackOverflow the name part is completely ignored. It's the id that is important. This works: access to article by article name in ASP.NET MVC2 and links to this question. To generate links that contain the name in the URL you could define the following route:
routes.MapRoute(
"NameIdRoute",
"{controller}/{action}/{id}/{name}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional, name = UrlParameter.Optional },
new { id = #"\d+" }
);
And then:
<%: Html.ActionLink("some text", "action", new { id = Model.Id, name = Model.Name }) %>
Create a route that allows the name to be specified as part of the url. Note that it's probably not actually used in resolving the article as it might not be unique. The id is the bit of information that is actually used to find and display the correct article, but the name is part of the url for context.
routes.MapRoute(
"Question",
"{controller}/{id}/{name}",
new { controller = "questions", action = "show", id = UrlParameter.Optional, name = UrlParameter.Optional },
new { id = "[0-9]+" } // constraint to force id to be numeric
);
Now, when you use Html.ActionLink() and specify the name as a parameter, the route will match and put in the name as a component of the url instead of a query parameter.
<%= Html.ActionLink( "questions", new { id = Model.ID, name = Model.NameForUrl } ) %>
Note that if you have multiple routes that might match you may need to use RouteLink and specify the route by name. Also, order matters.

Entity Framework and Sorting

I'm trying to sort a list of entities using a GridView in ASP.NET, but I can't seem to get it working following examples. I have a property called Name on my entity, and I'm trying to sort by a specified column if given, or the Name column if the sortExpression is empty.
public static List<Product> GetProducts(int startRowIndex, int maximumRows, string sortExpression) {
using(var context = new ShopEntities()) {
var products = context.Products;
products.OrderBy("it."+(string.IsNullOrEmpty(sortExpression) ? "Name" : sortExpression))
.Skip(startRowIndex)
.Take(maximumRows);
return products.ToList();
}
}
I can't get it to sort though. The only other option seems to be doing a switch on the property name for every property in the entity and using a lambda.
OrderBy doesn't mutate the expression. It returns a new expression, which your code ignores. Change your code to:
products = products.OrderBy("it."+ //...