Auto-increment ID in create method in ASP.NET MVC - asp.net-mvc

I create a controller for Category table and have generated CRUD metods.
In the CREATE action method, how can I make the CategoryID input disappear, and after entering CategoryName, the CategoryID column will automatically increment when adding a new entry to the table.

You can just remove the controls (textbox and label) from your create view.
Additionally, you can remove it from the list of parameters the POST method is expecting example
Change this:
public ActionResult Create([Bind(Include = "CategoryID,CategoryName")] Category category)
to:
public ActionResult Create([Bind(Include = "CategoryName")] Category category)

Related

MVC Moving from one Model View to Another Model View

I am trying to move from one Model's view to another Model's view. I have a Person model and a BurnProject model. From my Person's Index view I have a "Select" link in which I would like for it to go the BurnProject's Index view. I have tried a couple of things neither have worked.
public ActionResult BurnProject()
{
//return View("~/Views/BurnProject.cshtml");
return RedirectToAction("Index", BurnProject);
}
From my Person's Index view I have a "Select" link in which I would
like for it to go the BurnProject's Index view
Why not create a link which navigates to the index action method of BurnProjectsController ?
So in your Person's index view, you may use the Html.ActionLink helper method.
#model Person
<h1>This is persons index view<h1>
#Html.ActionLink("Select","Index","BurnProjects")
This will generate html markup for an anchor tag which has href attribute set to "BurnProjects/Index".
If you want to pass some data from the person's index view to your BurnProject index action, you can use another overload of Html.ActionLink
#model Person
#Html.ActionLink("Select","Index","BurnProjects",new {#id=Model.Id},null)
Assuming your Person entity has an Id property(which you want to pass the value for) and your BurnProjects index action accepts an id param
public ActionResult Index(int id)
{
// return something.
}

How to get route parameter of Get from Post Action in ASP.NET MVC?

I have two methods, one Get and one related Post.
public ActionResult Edit(string id){...}
[HttpPost]
public ActionResult Edit(MyModel model){...}
In the Post Method, I wish to get the id parameter of the Get method. Is it possible?
Currently, what i am doing is passing the id as form parameter.
[HttpPost]
public ActionResult Edit(string id, MyModel model){...}
Any other method?
Typically, the ID would be part of your Model that is being edited. You were able to retrieve the correct model in the GET Edit method using the ID, and hence, it is likely part of your MyModel model parameter of the POST Edit method.
As long as your MyModel class contains that Id, then posting it from the view should bind it correctly.
M

Getting actionlink parameter out of route path

I'm trying to add a webform that allows the user to add a database entry with a specific foreign key.
I'm creating the link like this
<%= Html.ActionLink("Edit", "EditSub", new { id = id }) %>
and the resulting URL is http://localhost:3015/TumourGroup/CreateSub/2 (where 2 is the id I passed to the actionlink earlier). The question is, how do I retrieve the value of id from the URL? I'm using it to grab the "main" table so that I can create a new table entry that has a foreign key pointing to the "main" table.
Assuming that TumourGroup is the name of a controller, and you have a route that looks something like this:
routes.MapRoute(
"Default",
"{controller}, {action}, {id}",
new { controller="Home", action="Index", id="" }
)
Then in your TumourGroup controller, you just need a controller method that looks like this:
public ActionResult CreateSub (int id)
{
// blah
}
The parameter id will contain your id from the Url.
EDIT: To include the id when you are submitting a form:
public ActionResult CreateSub (TumourGroupSubcategory tumourSubgroupToCreate)
{
// blah
}
Add the id as a property to your TumorGroupSubcategory class.
In the form view you are submitting, include a hidden field that is named the same as the id in your TumorGroupSubcategory class, and populate it with your id field.
When your user submits the form, the Model Binder will pick up the field, and put it into the id property of tumourSubgroupToCreate automatically.
Have your controller function CreateSub take in int id
public ActionResult CreateSub (int id)
If you want to go to the form with this id, then post with a different set of data, you'd need two functions, differentiated by
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult CreateSub (int id)
The get is for navigating to your entry form, the post is called when the form posts.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CreateSub (TumourGroupSubcategory tumourSubgroupToCreate)
BELOW IS RESPONDING TO CLARIFICATION IN COMMENTS:
Well, if you forego the strongly typed view, you can just do
ViewData["id"] = id;
ViewData["subGroupToCreate"] = ...
Alternatively you can do it in the second form on the client side with Javascript or Jquery

MVC form action

I have a edit View - Product/Edit/1
1 being the Id of the Product.How can I set the action of the edit post in the View to the POST edit action
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int Id, FormCollection collection)
The form tag is prepopulated as
but I want to set it to /Product/Edit/1
I am using this
<%using (Html.BeginForm()){ %>
but know its not right.Can someone help me how to set the form action using the htmlhelper class extension method to the Url in the browser
If you look at the intellisense for creating a Form with the HtmlHelper you will see there are parameters for specifying routeValues (of type object). Here you can specify the ID.
Your Edit View will be strongly typed with your Product object so you can specify Model.ID.
<% using (Html.BeginForm("Edit", "Product", new { Id = Model.ID } %>
...

How do I add relational data to an ASP.net MVC data entity Create view?

Let's say I have a table of staff members, and a separate table of staff roles in a many-to-many relationship (ie, with a StaffMembersInRoles table in between). Using the ADO.net entity framework we have an object model like this:
alt text http://martindoms.com/img/datamodel.png
I have a StaffController controller with a create method and a Create view which is pretty much the standard automatically generated type. I want the create page to list the roles in the StaffRoles table with a checkbox next to each, and when the submit button is pressed these are added to the new StaffMember StaffRole IEnumable (and so the appropriate entries are made in the StaffMembersInRoles table). How would I go about this with a strongly-typed view?
This is how i'd do it:
Firstly, you need an array of all possible roles.
In the controller, i'd do something like this (i'm making some assumptions about your DAO):
ViewData["AllRoles"] = (StaffRole[])StaffRole.FindAll();
Then in your view, loop through the roles:
<% foreach (StaffRole Role in (StaffRole[])ViewData["AllRoles"]) { %>
<p>
<label>
<%= Html.CheckBox("Role_"+Role.RoleId.ToString()) %>
<%= Html.Encode(Role.RoleName) %>
</label>
</p>
<% } %>
Then in your POST controller, do something like this:
foreach (StaffRole Role in (StaffRole[])StaffRole.FindAll())
{
if (Request.Params["Role_"+Role.RoleId.ToString()]=="true")
MyStaff.Roles.Add(Role);
}
Hi the Problem with this approach is you don't really have a strongly type entity passed to the View. In this problem you need the StaffMember information and a list of all StaffRole entities. PS: I really dun like the approach of casting the list in the view : StaffRole[])ViewData["AllRoles"]
Basicly i will prefer to work with DTO.
DTO:
public StaffMemberDto
{
public int StaffMemberId { get; set; }
public IList<StaffRoleDto> AllStaffRoles { get; set;}
public IList<StaffRoleDto> MembersRolesAttached { get; set;}
}
public StaffRoleDto
{
public int RoleId {get; set;}
public string RoleName { get; set; }
}
Controller:
return View(StaffMemberDto);
So in the view you get all roles strongly typed:
foreach (var role in ViewDate.Model.AllStaffRoles)
{
...
}
And in the post you can send the StaffMemberDto with the good RoleDto already assigned in the view or you can do the Request trick to get the id of the checkboxes ticked.
Well in a view like this i will probably use jquery to request an addRole each time someone tick the box to add a role. It will add some ajax to your form and you will not have some postback.

Resources