Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC partial view and form action name

Tags:

asp.net-mvc

How do I create a partial view that has a form with assigned id? I got as far as:

using (Html.BeginForm(?action?,"Candidate",FormMethod.Post,new {id="blah"}))

Partial view is used for both Create and Edit so first parameter ?action? will be different. I can't figure out what value of ?action? supposed to be.


UPDATE:

I guess I was not clear enough with the question. What I ended up doing is splitting Request.RawUrl to get controller name and action name:

 string[] actionUrlParts = ViewContext.HttpContext.Request.RawUrl.Split('/');
 using (Html.BeginForm(actionUrlParts.Length >= 2? actionUrlParts[2] : "",
        actionUrlParts.Length >= 1 ? actionUrlParts[1] : "", FormMethod.Post, new { id = "blah" }))   

Kind of ugly but it works. Is there a better way to get an action name inside the partial view?

like image 646
Dmitriy Shvadskiy Avatar asked Mar 01 '23 20:03

Dmitriy Shvadskiy


1 Answers

Pass in the action to be performed via ViewData.

In your action that renders the view, create a ViewData item for the postback action. In your form reference this ViewData item to fill in the action parameter. Alternatively, you can create a view-only model that includes the action and the actual model as properties and reference it from there.

Example using ViewData:

using (Html.BeginForm( (string)ViewData["PostBackAction"], "Candidate", ... 

Rendering actions:

public ActionResult Create()
{
     ViewData["PostBackAction"] = "New";
     ...
}


public ActionResult Edit( int id )
{
     ViewData["PostBackAction'] = "Update";
     ...
}

Example using Model

public class UpdateModel
{
     public string Action {get; set;}
     public Candidate CandidateModel { get; set; }
}

using (Html.BeginForm( Model.Action, "Candidate", ...

Rendering actions:

public ActionResult Create()
{
     var model = new UpdateModel { Action = "New" };

     ...

     return View(model);
}


public ActionResult Edit( int id )
{
     var model = new UpdateModel { Action = "Update" };

     model.CandidateModel = ...find corresponding model from id...

     return View(model);
}

EDIT: Based on your comment, if you feel that this should be done in the view (though I disagree), you could try some logic based off the ViewContext.RouteData

<%
    var action = "Create";
    if (this.ViewContext.RouteData.Values["action"] == "Edit")
    {
        action = "Update";
    }
    using (Html.BeginForm( action, "Candidate", ... 
    {
 %>
like image 67
tvanfosson Avatar answered Mar 07 '23 04:03

tvanfosson