How to let partial view call the action of the controller in area using "#Url.Action" - asp.net-mvc-5

I have tried to let partial view(_CartPartial.cshtml) call the action of the controller(OrderController.cs) in area using "#Url.Action" .
But the browser shows : Not Found View: 'Index'.
the code shown as follows:
_CartPartial.cshtml
**<a id="CartDropDown" class="btn-group btn-group-lg" href="#Url.Action("Index", "Order", new { })">
</a>**
OrderController.cs
**public class OrderController : Controller
{
// GET: Order
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index( Models.Order.Ship postback )
{
return View();
}
}
}**
the folder shown as follows:

can you use
#html.ActionLink("link text", "Action Name", "Controller Name");

Related

#html.dropdown onchange event MVC5

I have a View with a dropdownlist. I would like to select a value from the dropdownlist and depending on that value pull into the View a form related to that selection.
Looks like this:
I would like the form to appear below this ddlist and if the user changes the value in the ddlist, it would change the form.
Here's my "Add" View:
<div id="matSelContainer">
#Html.Action("SelectMaterial", "Materials", "Materials")
</div>
Here's the "SelectMaterial" View:
#model Procurement.Models.Material.MaterialType
#Html.Label("Select a Material Type: ")
#Html.DropDownListFor(
x => x.MaterialTypeList,
new SelectList(Model.MaterialTypeList, "MaterialTypeId", "Name")
)
Here's my Controller:
public ActionResult Add()
{
return View();
}
public ActionResult SelectMaterial()
{
materialTypes.LoadMaterialTypes();
return PartialView(materialTypes);
}
I would like to have a separate View for each Material Type and just call that View based on the selection in the ddlist.
Can someone show me how to achieve this?
Would I add a separate #Html.Action to the "Add" View and then in the Controller have another action return a PartialView?
But how to connect this with the Onchange event?
Update<<
Here's what is almost working for me:
"SelectMaterial" View:
#model Procurement.Models.Material.MaterialType
#Html.Label("Select a Material Type: ")
#Html.DropDownListFor(
x => x.MaterialTypeList,
new SelectList(Model.MaterialTypeList, "MaterialTypeId", "Name"),
new { #onchange="CallChangefunc(this.value)" })
<script>
function CallChangefunc(val) {
//alert("i am a " + obj.options[obj.selectedIndex].text);
//alert(obj.options[obj.selectedIndex].text);
window.location.href = "/Materials/MyMethod/" + val;
}
</script>
In my Controller I have this ActionResult:
public ActionResult MyMethod(string value)
{
return PartialView();
}
My controller is getting called when I change selection but the value coming in is null. I can see on the browser address bar that the expected selected value is being passed. Why is it null in controller? (I tried adding an [HttpPost] to ActionResult with no luck.)

Asp.net MVC 5 passing model object to controller via ActionLink

I need some help/advise on how to make this work.
I need to pass the model from the view to the controller through an ActionLink
#Html.ActionLink("Radera", "DeleteTraffic", new { model = Model, trafficId = traffic.Id }, new { #class = "btn btn-link NoBorder NoBackGround" })
the method in the controller looks like this.
public ActionResult DeleteTraffic(CalendarModel model, int trafficId)
{
return View("EditDay", model);
}
I have not put any code in the method yet, I've only been debugging it to get the call to work. model is null when I press the button, trafficId is however correctly set. so what have I done wrong?
Edit 1:
I've changed the code according to the suggestions here.
#using (Html.BeginForm("DeleteTraffic", "Calendar", new {trafficId = traffic.Id})) {<input type="submit" value="Radera" class="btn btn-link NoBorder NoBackGround"/>}
[HttpPost]
[ValidateAntiForgeryToken]
[ActionName("DeleteTraffic")]
public ActionResult DeleteTraffic(int trafficId)
{
return View("EditDay", Model);
}
but DeleteTraffic is never reched, instead it calls the Main Action for this page.
// GET: Calendar
public ActionResult Calendar()
{
CalendarModel model = new CalendarModel {SelectedDate = DateTime.Today};
if (Request.HttpMethod == "POST")
{
if (!string.IsNullOrEmpty(Request.Form.Get("submit.SelectDate")))
{
model.SelectedDate = Convert.ToDateTime(Request.Form["selectedDate"]);
model.TrafficDates = TrafficData.GeTrafficDatesPerMonth(model.SelectedDate);
Model = model;
return View("EditDay", Model);
}
}
Model = model;
return View(Model);
}
should I just tuck the trafficId into a hiddenfield and use this action for everything? MVC seems so inflexible at times...
First, something like a "delete" should never be handled by GET. Deleting is atomic and should be done utilizing either the POST or DELETE (preferably) verbs. Generally, you also should not just delete something without user confirmation, so the simplest and correct way to handle this would be to have the "delete" link take the user to a view that asks them to confirm deleting the item. On this view, then, you would submit the id of the item to be deleted via a form post:
public ActionResult Delete(int id)
{
var foo = db.Foos.Find(id);
if (foo == null)
{
return new HttpNotFoundResult();
}
return View(foo);
}
[HttpPost]
[ValidateAntiForgeryToken]
[ActionName("Delete")]
public ActionResult DeleteConfirm(int id)
{
var foo = db.Foos.Find(id);
if (foo == null)
{
return new HttpNotFoundResult();
}
db.Foos.Remove(foo);
db.SaveChanges();
return RedirectToAction("Index");
}
Then, for your GET action, you would add a Delete.cshtml file:
#model Namespace.To.Foo
<p>Are you sure you want to delete the foo, "#Model.Name"?</p>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.HiddenFor(m => m.Id)
#Html.ActionLink("Cancel", "Index")
<button type="submit">Delete</button>
}
Alternatively (or rather progressively, as you should still have the previous method as a fallback), you could use a JavaScript confirm and AJAX to do this, if you don't want to change pages:
#Html.ActionLink("Radera", "DeleteTraffic", new { id = item.Id }, new { #class = "btn btn-link NoBorder NoBackGround delete", data_id = item.Id })
Then:
<script>
$('.delete').on('click', function () {
var $deleteLink = $(this);
if (confirm('Are you sure?')) {
$.post('/url/for/delete/', { id = $deleteLink.data('id') }, function () {
$deleteLink.closest('tr').remove();
});
}
});
</script>

PartialView is not found

The controller is in /Areas/ShoppingCart/Controllers/
I've tried to let the controller return the PartialView which in /Views/Shared folder.
The Code as follows:
namespace MVCIIITourism.Areas.shoppingcart.Controllers
{
public class CartController : Controller
{
public ActionResult GetCart()
{
return PartialView("../../Shared/Views_Cartpatail.cshtml");
}
public ActionResult AddToCart(int id)
{
var currentCart = Operation.GetCurrentCart();
currentCart.AddProduct(id);
return PartialView("../../Shared/Views_Cartpatail.cshtml");
}
}
}
But the chrome shows the error message that is
Not Found PartialView in /Areas/ShoppingCart/Controllers/
How should I fix the problem?
If your partial is in the shared folder you don`t have to pass the entire path
Shared folder it`s access by all controllers
Simple use:
return PartialView("Views_Cartpatail.cshtml");

How to attach an existing View to a controller action?

How can I attach an existing View to an Action?
I mean, I've already attached this very View to an Action, but what I want is to attach to a second Action.
Example:
I've an Action named Index and a View, same name, attached to it, right click, add view..., but now, how to attach to a second one? Suppose an Action called Index2, how to achieve this?
Here's the code:
//this Action has Index View attached
public ActionResult Index(int? EntryId)
{
Entry entry = Entry.GetNext(EntryId);
return View(entry);
}
//I want this view Attached to the Index view...
[HttpPost]
public ActionResult Rewind(Entry entry)//...so the model will not be null
{
//Code here
return View(entry);
}
I googled it and cant find an proper answer...
It's possible?
you cannot "attach" actions to views but you can define what view you want be returned by an action method by using Controller.View Method
public ActionResult MyView() {
return View(); //this will return MyView.cshtml
}
public ActionResult TestJsonContent() {
return View("anotherView");
}
http://msdn.microsoft.com/en-us/library/dd460331%28v=vs.98%29.aspx
Does this help? You can use the overload of View to specify a different view:
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Index()
{
ViewBag.Message = "Hello I'm Mr. Index";
return View();
}
//
// GET: /Test/Index2
public ActionResult Index2()
{
ViewBag.Message = "Hello I'm not Mr. Index, but I get that a lot";
return View("Index");
}
}
Here is the View (Index.cshtml):
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>#ViewBag.Message</p>

WebApi Areas not found

I have a WebApi project and I am trying to add an area to it.
Is there something different that needs to be done when adding a new area to a webapi project vs a mvc4 application?
I have a simple area registration like
public class MobileAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Mobile";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Mobile_default",
"Mobile/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
A controller like
public class BusinessDetailsController : BaseController
{
public string Index()
{
return "hello world";
}
public HttpResponseMessage Get()
{
var data = new List<string> {"Store 1", "Store 2", "Store 3"};
return Request.CreateResponse(HttpStatusCode.OK, data);
}
}
However I can never reach the api. Am I doing something stupid or is there an extra step with the webapi that needs to be done?
Your code registers an MVC route for the Area, not a Web API route.
To do that use the MapHttpRoute extension method (you'll need to add a using statement for System.Web.Http).
public override void RegisterArea(AreaRegistrationContext context)
{
context.Routes.MapHttpRoute(
name: "AdminApi",
routeTemplate: "admin/api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
However, Areas are not really supported OOTB in ASP.NET Web API and you'll get an exception if you have two controllers with the same name (regardless of whether they are in different areas).
To support this scenario you need to change the way that controllers are selected. You'll find an article that covers how to do this here.

Resources