Passing Value to Controller in .Net Core - c#

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.

Related

#Html.AntiForgeryToken() with url.Action()

There is method in controller:
[HttpPost]
[ValidateAntiForgeryToken()]
public ActionResult RemoveFlag(Guid[] selected)
{
_presenter.RemoveFlag(selected);
return Json(new { Success = true });
}
It works fine with:
#using (Html.BeginForm("RemoveFlag", "controller", new { Area = "Area" }, FormMethod.Post))
{
#Html.AntiForgeryToken();
...
...
...
}
But this method is also used in my project's code with #Url.Action():
<ul>
<li>
<a
href="#Url.Action("RemoveFlag", "controller", new { Area = "Area"})"
data-target="km_grid_body"
data-redirect="#Url.Action("ManageCollections", "controller", new { Area = "Area" })"
>
Remove flag
</a>
</li>
</ul>
And this code doesn't work. Is there any ways to use Anti Forgery token validation within the #Url.Action()?

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

Why does Ajax.BeginForm load index again before partialview?

I am using Ajax.BeginForm to update a div with a partialview (loading logs based on the search input in the search fields).
The general idea is to load the Index the first time you log in with default values and then only update the log (partial view) when you search from there on.
The problem - When I debug my program it stops at Index in the controller before loading the partial view - resulting in long loading times.
The question - How can I make the Ajax request only load the partial view?
Code
_LogLayout.cshtml
<div id="log" class="tab">
<h1>Log</h1>
#using (Ajax.BeginForm("LogPartialView", "LogModelsController",
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "divLogs",
}, new
{
id = "NewTableId"
}))
{
<p>#Html.TextBox("SearchString", null, new { #placeholder = "Message" })</p>
if (Roles.IsUserInRole(WebSecurity.CurrentUserName, "Admin"))
{
<p>
#Html.DropDownList("SelectedCustomer", Model.LogModelVmObject.CustomerList, new { #id = "logdropdownlabel", #class = "dropdownlabels" })
</p>
}
<p>
<input type="submit" class="standardbutton logsearch" name="submit" value="Search" />
</p>
}
#using (Html.BeginForm("ExportData", "LogModels"))
{
<input type="submit" name="export" class="standardbutton export" value="Export to Excel" />
}
<div id="divLogs">
#Html.Raw(ViewBag.Data)
#Html.Partial("_LogPartialLayout")
</div>
</div>
</div>
LogModelsController.cs
/// <returns>
/// Returns the populated log with the current customers information if the user is of the Role Member,
/// otherwise if the user is in the Role Admin - then show all customers logs by default.
/// </returns>
public async Task<ActionResult> Index()
{
if (Session["myID"] == null)
return ExpireSession();
const int pageNumber = 1;
var lmvm = new LogModelVm { CurrentSort = null };
var myId = Convert.ToInt32(Session["myID"].ToString());
if (Roles.IsUserInRole(WebSecurity.CurrentUserName, "Admin"))
{
_customer = _cdvdb.GetAllCustomerIds();
_message = _db.GetLogs();
}
else if (Roles.IsUserInRole(WebSecurity.CurrentUserName, "Member"))
{
_message = _db.GetLogsById(myId);
}
var logs = _message.OrderByDescending(i => i.Timestamp).ToPagedList(pageNumber, PageSize);
if (Roles.IsUserInRole(WebSecurity.CurrentUserName, "Admin"))
{
if (_customer != null)
{
var selectListItems = _customer as SelectListItem[] ?? _customer.ToArray();
foreach (var log in logs)
log.Name = selectListItems.FirstOrDefault(a => a.Value == log.CustomerId.ToString())?.Text;
lmvm.CustomerList = selectListItems;
}
}
lmvm.Logs = logs;
var model = new LogStatisticsModel
{
LogModelObject = new LogModel(),
StatisticsModel = await StatisticsData.GetAllCurrentStatisticsValues(1, DateTime.Now),
LogModelVmObject = lmvm
};
return View(model);
}
/// <returns>
/// Returns a partial view of the log.
/// </returns>
[HttpPost]
public ActionResult LogPartialView(string searchString, int? selectedCustomer, string currentMessageFilter, string currentCustomerFilter, int? page, string sortOrder)
{
// Some code.
return PartialView("_LogPartialLayout", model);
}
RouteConfig.cs
using System.Web.Mvc;
using System.Web.Routing;
namespace MyProject
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Login", action = "Index", id = UrlParameter.Optional });
routes.MapRoute("Log", "{controller}/{action}/{Id}");
routes.MapRoute("Admin", "");
}
}
}
Index.cshtml
#model MyProject.Models.LogStatisticsModel
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
#{
ViewBag.Title = "MyPortal";
Layout = "~/Views/Shared/_LogLayout.cshtml";
}
After a long discussion with #StephenMuecke which (among a ton of useful things) told me to try and comment out every single javascript in the _LogLayout.cshtml file and one by one uncomment them back and see if any of them caused the problem.
I found that the following script caused the problem.
<script type="text/javascript">
$('#loadercheck').click(function ()
{
$('#loader').show();
$.ajax(
{
success: function ()
{
$('#loader').delay(1200).hide(400);
}
});
})
</script>
The following script was used to display a spinning loader while the log was loading data. Apparently this caused the Index() to be called again. So I will have to find a new way to display a loader now...

Getting value from view to HttpGet controller Action Method

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

How to change list of inputs in a form to a list of links?

How can I make the following code be a list of links instead of a list of buttons?
#foreach (var item in #Model)
{
using (Html.BeginForm(new { action = "GetL", controller = "L" }))
{
<input name="fileLocation" type="submit" value="#item" />
}
}
#foreach (var item in #Model)
{
using (Html.BeginForm(new { action = "GetL", controller = "L" }))
{
<a name="fileLocation" href="#item">#item</a>
}
}
You can use Html.ActionLink helper method to generate anchor tag
#foreach (var item in #Model)
{
using (Html.BeginForm(new { action = "GetL", controller = "L" }))
{
#Html.ActionLink(item,"yourAction","YourController")
}
}
If you want to pass some parameters ( Ex : Id ) to the Action method, you can do it with this override
#Html.ActionLink(item,"yourAction","YourController",
new { #id="someVal"} ,null)

Categories