Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
170
rated 0 times [  177] [ 7]  / answers: 1 / hits: 48557  / 10 Years ago, mon, october 6, 2014, 12:00:00

Hi I am pretty new to web development and am stuck on a specific scenario.



I have a Map controller with 2 methods:



public ActionResult Map1(double easting, double northing)
public ActionResult Map2(double easting, double northing)


When called they both navigate their corresponding view with whatever model is required:



return View(model);


I then have some javascript which needs to call the corresponding controller method depending on the action passed through.



I want to mark the controller methods as [HttpPost], but when I do this then use an ajax request in the javascript the call to the View gets swallowed and the page is not redirected.



Currently the only way I have got it to work is by this:



window.location.href = '/Map/' + actionVal + '?easting=' + easting + '&northing=' + northing;


But with using this I cannot set the methods as POST.



Does anyone have a better idea of how I should do this?


More From » ajax

 Answers
25

Does anyone have a better idea of how I should do this?




Actually there is no need for you to have TWO different Controller actions, instead you can have only ONE. And this action is going to return a view which you want to display.



One way to make a POST is to use HTML.BeginForm() and pass Controller and Action names along with FormMethod.POST to BeginForm(). Inside the BeginForm, you can have a HTML Input Button of type Submit to make the POST call to Controller action.



Also if you want to differentiate the invocation of this controller action, I would suggest you something like this -



First construct you model like this with Type variable through which you can differentiate the operation you need to perform on data -



public class Details
{
public string easting { get; set; }
public string northing { get; set; }
public string type { get; set; }
}


And let your controller action be defined like this -



[HttpPost]
public ActionResult Map(Details details)


And you can have your view define a HiddenField like this -



@model Namespace.Details

@{
ViewBag.Title = Title;
}

<div id=uploadCourseList>
@using (Html.BeginForm(Action, Controller, FormMethod.Post))
{
@* Other properties of Model *@
@Html.HiddenFor(m => m.type)
<input type=submit>
}
</div>


Now on the view set the type, so that you can differentiate the post operation and perform necessary calculations on your data and return the view.


[#69228] Friday, October 3, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mckenna

Total Points: 445
Total Questions: 109
Total Answers: 109

Location: Virgin Islands (U.S.)
Member since Sun, May 16, 2021
3 Years ago
;