passing an id to Create of other model - asp.net-mvc

In this actionLink I get the id from Cliente.
#Html.ActionLink("Pets", "Create", "Pets", new {id = Model.ClientId}, null)
Than i send this id to a view bag in PetController
public ActionResult Create(int id)
{
ViewBag.ClienteId = new SelectList(db.Clientes, "ClienteId", "Nome");
return View();
}
But when a run the code, the dropdown show more than one Client.
As you can see in this image.
how can i show only de client who have the id that a i get in the actionlink ?
Thank's.

At Html
#Html.ActionLink("Pets", "Create", "Pets", new {id = Model.ClientId}, null)
At PetController
public ActionResult Create(int id)
{
ViewBag.ClienteId = new SelectList(db.Clientes, "ClienteId", "Nome");
return View();
}

Related

Url.Action map a wrong link from Route attribute

This is target controller and action:
[RoutePrefix("Editor")]
public class EditorController : Controller
[HttpGet]
[Route("{id:int}")]
public ActionResult Edit(int id)
Map method calling:
#Url.Action("Edit", "Editor", new { id = page.Id})
result:
/Editor?id=1
required result:
/Editor/1
To achieve the result you want you have to use a route name:
[HttpGet]
[Route("{id:int}", Name = "EditorById")]
public ActionResult Edit(int id)
Then in your view you would use Url.RouteUrl instead of Url.Action:
#Url.RouteUrl("EditorById", new { controller = "Editor", Id = 1, action = "Edit" })
Hope this helps,
Have you checked if you have enabled MVC AttributeRoutes?
routes.MapMvcAttributeRoutes();
see http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx
I just faced with same problem. When i fixed the links - editing is broken (form always redirects to the same page).
Here is solution:
A link
#Html.ActionLink("Edit my nice object", "Edit", new { id=item.Id })
A form in the view Edit.cshtml (specifying Controller name is necessary!)
#using (Html.BeginForm("EditConfirmed", "AppServers"))
The actions in the controller
public class AppServersController
[Route("edit/{id:int?}")]
public ActionResult Edit(int? id)
{
// bla-bla
}
[Route("edit_confirmed")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditConfirmed([Bind(Exclude = "Created,LastModified")] AppServerVM appServer)
{
if (!ModelState.IsValid) return View("Edit", appServer);
// bla-bla
}
}
Now both links and editing works.

ReturnUrl has no value, ASP.Net MVC

I've faced some problem recently and couldn't find the solution. I'm working on SportsStore from Adam Freeman's book Pro MVC 4. Look at this please:
I have a View called Index:
#model WebUI.Models.CartIndexViewModel
.
.
.
<p align="center" class="actionButtons">
Kontynuuj zakupy
</p>
CartController:
{
public class CartController : Controller
{
private IProductRepository repository;
public CartController(IProductRepository repo)
{
repository = repo;
}
public ViewResult Index(string returnUrl)
{
return View(new CartIndexViewModel
{
Cart = GetCart(),
ReturnUrl = returnUrl
});
}
public RedirectToRouteResult AddToCart(int productID, string returnUrl)
{
Product product = repository.Products.FirstOrDefault(p => p.ProductID == productID);
if (product != null)
{
GetCart().AddItem(product, 1);
}
return RedirectToAction("Index", new { url = returnUrl });
}
public RedirectToRouteResult RemoveFromCart(int productId, string returnUrl)
{
Product product = repository.Products.FirstOrDefault(p => p.ProductID == productId);
if (product != null)
{
GetCart().RemoveLine(product);
}
return RedirectToAction("Index", new { url = returnUrl });
}
private Cart GetCart()
{
Cart cart = (Cart)Session["Cart"];
if (cart == null)
{
cart = new Cart();
Session["Cart"] = cart;
}
return cart;
}
}
}
ProductSummary View:
#model Domain.Entities.Product
<div class="item">
<h3>#Model.Name</h3>
#Model.Description
#using (Html.BeginForm("AddToCart", "Cart"))
{
#Html.HiddenFor(x => x.ProductID)
#Html.Hidden("returnUrl", Request.Url.PathAndQuery)
<input type ="submit" value="+ Dodaj do koszyka"/>
}
<h4>#Model.Price.ToString("c")</h4>
</div>
and CartIndexModelView:
public class CartIndexViewModel
{
public Cart Cart { get; set; }
public string ReturnUrl { get; set; }
}
And my problem is actually that my Kontynuuj zakupy
returns empty <a>KontunuujZakupy</a> Html, which I guess means that #Model.ReturnUrl doesn't get any value at all. I couldn't figure out why because i am begginer, would You mind to give me a clue about that? Thanks.
//edit
"Kontynuuj zakupy" means Continue Shopping :)
Your index action looks like this:
public ViewResult Index(string returnUrl) { ... }
It takes the parameter of returnUrl and insert that into the model which you return. If you browse to your website without specifying a return URL, it will be blank, for example:
http://localhost:1234
http://localhost:1234/Home/Index
Try passing a parameter like this:
http://localhost:1234?returnUrl=xxxx
http://localhost:1234/Home/Index?returnUrl=xxxx
Notice that the parameter name matches the index action. So in your AddToCart and RemoveFromCart actions, you need to change the name of the parameter from url to returnUrl.
return RedirectToAction("Index", new { returnUrl = returnUrl });
you can simply change the last line of your AddToCart action to:
return RedirectToAction("Index", new { returnUrl = returnUrl });

Is viewbag the best option?

I am trying to construct an #Html.ActionLink to return to a previous page but to return to the previous page I need to pass in an id parameter.
ShowController/Details list a film defined by a int id, within this list is a link to go and look at the director details:
#Html.ActionLink( "(Director Bio)", "Index", "Director", new { searchString = item.Director.Name }, null)
When the user wants to go back to the film the StoreController/Details ActionResult is waiting for an int it.
I have tried to pass in the id to a viewBag:
public ActionResult Details(int id)
{
var item = from s in db.Shows.Where(si => si.ShowId == id) select s;
ViewBag.id = id;
return View(item);
}
And this shows fine in the Details view I cannot pick it up in the DirectorController/Index view to use in the actionLink, what do I do?

ASP.NET MVC ModelState.IsValid doesnt work

I've this controller's method for create
[HttpPost]
public ActionResult Create(Topic topic)
{
if (ModelState.IsValid)
{
topicRepo.Add(topic);
topicRepo.Save();
return RedirectToAction("Details", new { id = topic.ID });
}
return View(topic);
}
and this for edit
[HttpPost]
public ActionResult Edit(int id, FormCollection formCollection)
{
Topic topic = topicRepo.getTopic(id);
if (ModelState.IsValid)
{
UpdateModel<Topic>(topic);
topicRepo.Save();
return RedirectToAction("Details", new { id = topic.ID });
}
return View(topic);
}
Both of these methods use common partial page (.ascx).
Validation works when I try to create topic but doesn't work when I try to edit it
That's normal. In the first example you are using a model as action parameter. When the default model binder tries to bind this model from the request it will automatically invoke validation and when you enter the action the ModelState.IsValid is already assigned.
In the second example your action takes no model, only a key/value collection and without a model validation makes no sense. Validation is triggered by the UpdateModel<TModel> method which in your example is invoked after the ModelState.IsValid call.
So you could try this:
[HttpPost]
public ActionResult Edit(int id)
{
Topic topic = topicRepo.getTopic(id);
UpdateModel<Topic>(topic);
if (ModelState.IsValid)
{
topicRepo.Save();
return RedirectToAction("Details", new { id = topic.ID });
}
return View(topic);
}

Post action Create in asp.net MVC

i'm using MS northwind database, and use Entity Framework.
I want to create new product, and use dropdownList to load CategoryName from Category Table.
public ActionResult Create()
{
var categories = from c in _en.Categories select c;
ViewData["CategoryID"] = new SelectList(categories, "CategoryID", "CategoryName");
return View();
}
<p>
<label for="ds">CategoryID:</label>
<%=Html.DropDownList("CategoryID", (SelectList)ViewData["CategoryID"])%>
</p>
Question: How to Save data from dropdownList?
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "ProductID")] Products productToCreate)
{
if (!ModelState.IsValid)
return View();
var c = _en.Categories.FirstOrDefault(z => z.CategoryID == ??? XXXX ???);
productToCreate.Categories = c;
_en.AddToProducts(productToCreate);
_en.SaveChanges();
return RedirectToAction("Index");
}
how to get CategoryID from dropdownList?
Just add CategoryID to the arguments.
public ActionResult Create([Bind(Exclude = "ProductID")] Products productToCreate, string CategoryID)

Resources