How to attach an existing View to a controller action? - c#-4.0

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>

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.)

Delete function doesn't work in MVC application-Does not delete from DB?

I'm trying to make a delete function in my application that the user should be able to delete a product from the table but when the user presses the delete button, the error message "InvalidOperationException: Cannot remove an entity that has not been attached" comes up. I can't figure out what the problem is because it get's the product the user want's to delete(and displays it in the view) but when it get's to the HttpPost method, (when the user confirms that he want's to delete this product by pressing the delete button), the error message comes up... All the other methods work(create,edit,list...)only the delete method doesn't. I would really appreciate if someone can help me with this.
this is my code:
[HttpGet]
public ActionResult Delete(int id)
{
var p= prodRepo.GetProductById(id);
return View(p);
}
[HttpPost]
public ActionResult Delete(Product product)
{
prodRepo.DeleteProduct(product);
return RedirectToAction("Index");
}
this is the code from the productRepository class...
public Product DeleteProduct(Product product)
{
db = new NorthwindDataContext();
db.Products.DeleteOnSubmit(product);
db.SubmitChanges();
return product;
}
public Product GetProductById(int id)
{
db = new NorthwindDataContext();
var prod = (from p in db.Products
where p.ProductID==id
select p).Single();
return prod;
}
Just pass the id of product in delete action
[HttpPost]
public ActionResult DeleteConfirmed(int id)
{
Product_Table Ptobj = db.Product_Table.find(id);
db.Product_Table.remove(Ptobj);
db.savechanges()
}

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 let partial view call the action of the controller in area using "#Url.Action"

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");

Account Controller error

Hello guys I have a problem in the Account Controllers wanted to add a method for viewing jobs for employees, but now it is giving me an error "Not all code paths return a value"
public ActionResult ViewAssignJob()
{
var userId = User.Identity.GetUserId();
var jobs = _jobService.GetEmployeeJobs(userId);
}
Your method's return type is ActionResult
public ActionResult ViewAssignJob()
{
}
In these type of method you generally return View() or return View(viewmodel).
If you don't want to return view for some debugging purpose, you could also return content("hello world") this will result to Hello world in a blank page
Return View() from Actionresult and your error will gone.
public ActionResult ViewAssignJob()
{
var userId = User.Identity.GetUserId();
var jobs = _jobService.GetEmployeeJobs(userId);
return View(); // or // return View(Model);
}
hey you just forgot one important line as your error suggest, just put a return statement in your method so that it returns what you want. after this I am sure you will not be experiencing any problem.
here is how your code should look like!
public ActionResult ViewAssignJob()
{
var userId = User.Identity.GetUserId();
var jobs = _jobService.GetEmployeeJobs(userId);
return View(jobs);
}

Resources