Getting value from view to HttpGet controller Action Method - c#

Here my view.i want to pass TempData[Id] to HttpGet controller action method Index.how can i pass this values.pleae help me.thanks in advance
#if (TempData["Id"] != null)
{
using (Html.BeginForm("Index", "QuestionnaireController", FormMethod.Get))
{
<p>#SixSeconds.App_GlobalResources.Frontend.DeleteQuestionnaire</p> <input type = "submit" value = "#SixSeconds.App_GlobalResources.Frontend.OK"/>
}
}
[HttpGet]
public ActionResult Index(string idQ, string idTT, string easyLoad)
{
Project project = _getProject(idQ);
ViewBag.LanguageCode = project.ItemLanguage.Code;
ViewBag.projectType = project.ProjectType.ToString();
per ricevere un questionario
int reportCredits = 0;
foreach (ProjectReportOption pro in project.ProjectReportOptions)
{
reportCredits += pro.Display && pro.ReportType != null ? pro.ReportType.Credits : 0;
}

You can pass the data as route values:
#using (Html.BeginForm("Index", "QuestionnaireController", new { idQ = TempData["Id"] }, FormMethod.Get))
{
}
And you need to define the route:
routes.MapRoute("NameOfThisRoute",
"QuestionnaireController/Index/{idQ}",
new { controller = "QuestionnaireController", action = "Index" });

Related

Passing Value to Controller in .Net Core

I have a requirement to pass value from view to controller in the Html.BeginForm()
#using (Html.BeginForm("ChangeRole", "Login", null, FormMethod.Post, null, new { id = "SubmitRole" }))
{
#Html.AntiForgeryToken()
#foreach (var item in (#HttpContextAccessor.HttpContext.Session.GetObjectFromJson<UserRoleLevelDetails>("GetAllUsersList")))
{
//..
if (#vr != #HttpContextAccessor.HttpContext.Session.GetString("Role").ToString())
{
<a class="#vr" id=#string.Format("{0}", #item.Role_Level_Name) onclick="Change_Role(this)">#vr</a><br />
}
//..
}
}
function Change_Role(e) {
var ChangedRole = $(e).attr('class');
$('#UserMainRole').val(ChangedRole);
$("#SubmitRole").submit();
e.preventDefault();
};
So, while submitting I need to pass value of ChangedRole to the controller.

How to pass checkbox value to controller in ASP.NET MVC

I am using
#Html.CheckBoxFor(model => model.AllowOrder, new { id = "allowOrder"})
Now I want to pass its value (whether checked or unchecked) to the controller. I am using html.BeginForm for posting back the data to controller. Every time I am getting its value as null in action method. Action method has below sample code.
public ActionResult index(bool isChecked)
{
// code here
}
isChecked property is passed in as null always. Any help please. TIA.
If you don't want to return to controller whole data model, but only one value then see code below:
public IActionResult IndexTest()
{
var model = new ViewModel() { AllowOrder = true };
return View(model);
}
[HttpPost]
public IActionResult IndexTest(bool isChecked)
{
// your code here...
return View("IndexTest", new ViewModel() { AllowOrder = isChecked} );
}
Using the onclick() to trace the checkbox state:
#model ViewModel
<script>
function onStateChange() {
var item = document.getElementById('allowOrder');
var chk = false;
if (item.checked) {
chk = true;
}
document.getElementById('isChecked').value = chk;
};
</script>
#using (Html.BeginForm())
{
#Html.Hidden("isChecked", Model.AllowOrder)
#Html.CheckBoxFor(r => Model.AllowOrder, new { id = "allowOrder", #onclick = "onStateChange()" })
<input id="Button" type="submit" value="Save" />
}
View:
#model <specifyModelhere>
#using(Html.BeginForm("index","<YourControllerNameHere>",FormMethod.Post))
{
#Html.CheckBoxFor(r => Model.AllowOrder)
<input id="Button" type="submit" value="Save" />
}
Controller:
public ActionResult index(<YourModelNameHere> model)
{
var ischecked = model.AllowOrder;
// code here
}
This way when you submit the form, the entire model will be posted back and you can receive it in the controller method

Pass in data parameters to new MVC ActionResult call without showing in URL

I am working with adding a new MVC page and have the method and calls up and running. My issue is that I am not wanting to pass in URL parameters to show in my page but need to pass in the parameters for the method when I do a redirect to my new page. Currently I have it set up like this:
Page.cs
void ToNewPage()
{
Response.RedirectToRoute(new { controller = "ControllerName", action = "ActionName", ID1 = 1, ID2 = 2 });
}
ControllerName.cs
public ActionResult ActionName(int ID1, int ID2)
{
...
return View(model);
}
Currently with my code I get the URL ~/ControllerName/ActionName?ID1=1&ID2=2. I am just wanting the URL to just be ~/ControllerName/ActionName. I know this would be easier on a frontend or maybe through javascript but needing to do this from the ToNewPage method if possible.
There are working codes:
PageController.cs
public class PageController : Controller
{
// GET: Page
public ActionResult Index()
{
return View();
}
public ActionResult ToNewPage()
{
var ids = Newtonsoft.Json.JsonConvert.SerializeObject(new { ID1 = 1, ID2= 2 });
TempData["ids"] = ids;
return RedirectToAction("Index", "NewPage");
}
}
NewPageController.cs
public class NewPageController : Controller
{
// GET: NewPage
public ActionResult Index()
{
if (TempData["ids"] != null)
{
dynamic ids = JsonConvert.DeserializeObject(TempData["ids"] as string);
ViewBag.ID1 = ids.ID1;
ViewBag.ID2 = ids.ID2;
}
return View();
}
}
NewPage\Index.cshtml
#{
ViewBag.Title = "Index";
}
<h2>NewPage</h2>
<ul>
<li>ID1: #ViewBag.ID1</li>
<li>ID2: #ViewBag.ID2</li>
</ul>
You should use TempData:
void ToNewPage()
{
TempData["ID1"]="ID1 Value"
TempData["ID2"]="ID2 Value"
Response.RedirectToRoute(new { controller = "ControllerName", action = "ActionName"
});
}
public ActionResult ActionName()
{
int ID1=int.parse(TempData["ID1"].ToString());
int ID2=int.parse(TempData["ID2"].ToString());
return View();
}
You can fill many TempDatas in many controllers and use them in many Views and controllers

Parameter passed to post controller is always null

This question is really similar to my last one but this has to do with passing multiple parameters. My controller has two methods with the same name but one gets passed a nullable int to determine which action to take on post (I don't know if that's a good design decision). Here's the code:
public ActionResult EventDetails(int? eventID)
{
EventDetailsViewModel model = new EventDetailsViewModel();
if (eventID != null)
{
model.afterPost = false;
model.currentAttendance = getCountAttending(eventID);
model.currentUser = getCurrentUserProfile(User.Identity.Name);
model.eventDetails = getEventDetails(eventID);
model.eventRestrictions = getEventRestrictions(eventID);
model.usersAttending = getUsersAttending(eventID);
return View(model);
}
else
{
return View();
}
}
[HttpPost]
public ActionResult EventDetails(int? eventID, int? action)
{
EventDetailsViewModel model = new EventDetailsViewModel();
if (eventID != null)
{
model.afterPost = true;
model.currentAttendance = getCountAttending(eventID);
model.currentUser = getCurrentUserProfile(User.Identity.Name);
model.eventDetails = getEventDetails(eventID);
model.eventDetails["ActionID"] = action.ToString();
model.eventRestrictions = getEventRestrictions(eventID);
model.usersAttending = getUsersAttending(eventID);
return View(model);
}
else
{
return View();
}
}
the view is huge but I'll post the relevant piece:
#if(User.Identity.IsAuthenticated)
{
if (!Model.eventDetails["Event_Owned"].Equals("true"))
{
<div class="joinEventButton">
#if(Model.eventDetails["Event_Current"].Equals("true"))
{
<form method="post" action="#Url.Action("EventDetails", "Event", new{eventID = Int32.Parse(Model.eventDetails["EventID"]), action = Int32.Parse(Model.eventDetails["CODE_RequestInvitation"])})">
<input type="submit" value="Request Invitation" class="submitButton submitButton-green"/>
</form>
}
else
{
<button class="disabledButton disabledButton-grey">Request Invitation</button>
}
</div>
}
and just for good measure, my routes:
public static void RegisterRoutes(RouteCollection routes)
{
//routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
So the idea is that based on authentication and whether they own a specific event they are looking at, they will have different buttons show on the screen. This certain one is for when they want to join an event they can push a button to request an invitation. The controller knows this because of the int value being passed back as CODE_RequestInvitation. The action being returned is always null. I can't figure out what's wrong.
You problem is the use of the parameter name action (which is conflicting with the action attribute). Change it to another name and it will work. Inspect he html of the <form> element before and after the change.
You code for generating the form is awful and the use of Int32.Parse() is pointless.
#using (Html.BeginForm("EventDetails", "Event", { eventID = Model.eventDetails["EventID"], actionID = Model.eventDetails["CODE_RequestInvitation"] }, FormMethod.Post))
{
<input type="submit" value="Request Invitation" class="submitButton submitButton-green"/>
}
and post back to
[HttpPost]
public ActionResult EventDetails(int? eventID, int? actionID)

on asp.net mvc 3 using the razor engine, what's the best practice to pass data between multiple views?

first of all, sorry for my english
I am new to ASP.NET MVC and was trying to develop a simple web application using the Razor Engine
so I have this view called Extract, which accepts an url as input:
#using (Html.BeginForm("Begin", "Rss"))
{
#Html.LabelFor(m => m.Url) #Html.TextBoxFor(m => m.Url)
<button>Extrair</button>
}
when submited, it will send the url to my controller:
public ActionResult Begin(ExtractModel m)
{
if (ModelState.IsValid)
{
var extractedData = ExtractorService.Extract(m.Url);
if (extractedData != null)
{
TempData["extractedData"] = extractedData;
return RedirectToAction("Extracted", extractedData);
}
}
return View();
}
then a new view called Extracted will show all the links extracted from the rss passed:
public ActionResult Extracted(ExtractedModel m)
{
if (TempData["extractedData"] != null)
{
ViewData["extractedData"] = TempData["extractedData"];
return View(ViewData["extractedData"] as ExtractedModel);
}
else
{
return RedirectToAction("Extract");
}
}
-
#using (Html.BeginForm())
{
foreach (var data in Model.Data)
{
<ul>
<li>#data.Link</li>
</ul>
}
<button>Converter</button>
}
bottom line what I want to ask is: how do I get the ViewData["extractedData"] which I set when loading this View so I can pass it back to the controller and parse all the info inside of it? because when I click on the button Converter my ViewData is empty and I can't process anything without it =\
I wouldn't use TempData for passing complex objects between the views. I would also get rid of ViewData.
Then I would rather have the controller action rendering the view fetch whatever information it needs:
public class RssController: Controller
{
public ActionResult Extract()
{
var model = new ExtractModel();
return View(model);
}
[HttpPost]
public ActionResult Begin(string url)
{
if (ModelState.IsValid)
{
return RedirectToAction("Extracted", new { url = url });
}
return View();
}
}
have the corresponding view which allows for entering the url (~/Views/Rss/Extract.cshtml):
#model AppName.Models.ExtractModel
#using (Html.BeginForm("Begin", "Rss"))
{
#Html.LabelFor(m => m.Url)
#Html.TextBoxFor(m => m.Url)
<input type="submit" value="Extrair" />
}
and in the other action you are redirecting to:
public ActionResult Extracted(string url)
{
var extractedData = ExtractorService.Extract(url);
if (extractedData != null)
{
return View(extractedData);
}
return RedirectToAction("Extract");
}

Categories