MVC 4: Calling action method on dropdown list select change - c#

I have a dropdown list, and I want a specific action method to be called on changing selection. Here is my dropdown list:
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "ediFilesForm" }))
{
var directoriesSelectList = new SelectList(Model.Directories);
#Html.DropDownListFor(m => m.SelectedDirectory, directoriesSelectList, new {#Id = "Directories", #style = "width:Auto;height=Auto;", #size = 10, onchange = "$('#ediFilesForm').submit()", name="action:FolderChange"})
And here is the action method:
[HttpPost]
[ActionName("FolderChange")]
public ActionResult FolderChange(EdiFileModel ediFileModel)
{
//do your work here
return View("Index", ediFileModel);
}
For some reason, this method is never hit, but this one is hit instead:
public ActionResult Index()
{
...
return View(ediFileModel);
}
What can I try next?

First parameter of the BeginForm method is Action name, second one is the Controller.You are passing null so it uses default values.
Change your code and pass name of the Action that you want to call:
#using (Html.BeginForm("FolderChange", "ControllerName", FormMethod.Post, new { id = "ediFilesForm" }))

try below code :-
#using (Html.BeginForm("FolderChange", "ControllerName", FormMethod.Post, new { id = "ediFilesForm" }))
{
////your code
}
the problem occurs because you are not passing enough information in beginform.
for more information :-
How to write "Html.BeginForm" in Razor

Related

ASP .NET MVC 5 - How to add form model inside Ajax.ActionLink?

I'm working on the table paging, where each page calls the controller to get part of the data, then return the partial view and update it into HTML table.
Here's my controller look like:
public ActionResult SearchData(FormModel model, int? page)
{
/*Codes to get data from DB*/
return PartialView("_DataTable", model);
}
The form input is something like this:
#model Project.ViewModel
#using (Ajax.BeginForm("SearchData", "Player", new AjaxOptions
{ HttpMethod = "GET", UpdateTargetId = "data-table", InsertionMode = InsertionMode.Replace }))
{
#Html.LabelFor(m => m.FormModel.Username)
#Html.TextBoxFor(m => m.FormModel.Username, new { placeholder = "[Username]" })
#*And some more input, all are in FormModel class.*#
}
<div id="data-table">
#Html.Partial("_DataTable")
</div>
The way I generate the page is as follows:
for (var pageNum = Model.PlayerList.Pager.StartPage; pageNum <= Model.PlayerList.Pager.EndPage; pageNum++)
{
if (pageNum == Model.PlayerList.Pager.CurrentPage)
{
<td><span>#pageNum</span></td>
}
else
{
<td>
#Ajax.ActionLink(pageNum.ToString(), "SearchData", new {page = pageNum}, new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "data-table"
})
</td>
}
}
I can only pass in the page value, is it possible to include the form input Model into Ajax.ActionLink? Something like this:
new {model = Model.FormModel, page = pageNum}
I tried the method above, but didn't work. Any help would be appreciated.
you need add properties of FormModel like this
new {Username="some username",page = pageNum}
I came out with another solution. I put the form model inside TempData just before the controller returns the partial view. At the beginning of the controller, I check if the page value is null, the form input should take from TempData instead. This way, we only pass in the page value since the form input model should always the same, using Ajax.ActionLink as I posted on the question.
Here's the code:
public ActionResult SearchData(FormModel model, int? page)
{
if (page != null)
{
model = TempData["FormModel"] as FormModel ?? new FormModel();
}
/*Codes to get data from DB*/
TempData["FormModel"] = model;
return PartialView("_DataTable", model);
}
do it like this and change fields names and values as your model
note: unfortunately, you should send each value one by one, but not the whole model
#Ajax.ActionLink(pageNum.ToString(), "SearchData",
new
{
FielNameInModel1= Model.FieldNameInModel,
FielNameInModel2 = "xyz",
FielNameInModel3 = 5,
FielNameInModel4 = pageNum.ToString(),
},
new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "AllProjectsDiv", OnComplete = "AjaxFormCompleted" }
, new { #class = "className") })

Sending a SelectList Selection to a Create View from a Layout Modal MVC 5

I have a small view inside of an HTML.Action that lives inside my _Layout. I am trying to send the ProjectId of the selected project to the Create Ticket View. My modal view looks like this.
Here is the controller method for the modal view:
[AllowAnonymous] // Change this to only submitters
public ActionResult NavRoleItems()
{
ViewBag.ProjectId = new SelectList(db.Projects, "Id", "Name");
return View();
}
Modal View
#using (Html.BeginForm("Create", "Tickets", FormMethod.Get))
{
#Html.AntiForgeryToken()
<div class="modal-body">
#Html.DropDownListFor(p => p.ProjectId, null, new { #class = "form-control"})
</div>
<div class="modal-footer">
<input type="submit" value="Add Issue" />
</div>
}
And I want to send any way I can really, but Ideally I want to send it as the projId variable below. Im in school and this is the first time I have played with Formmethod.Get.
Controller View
public ActionResult Create(string projId)
{
TicketCreateViewModel model = new TicketCreateViewModel();
var userId = User.Identity.GetUserId();
var user = db.Users.Find(userId);
model.OwnerUserId = userId;
model.OwnerUser = user;
model.ProjectId = projId;
model.AssignedToUserId = new SelectList(db.Users, "Id", "FirstName");
ViewBag.TicketPriorityId = new SelectList(db.TicketPriorities, "Id", "Name");
ViewBag.TicketStatusId = new SelectList(db.TicketStatuses, "Id", "Name");
ViewBag.TicketTypeId = new SelectList(db.TicketTypes, "Id", "Name");
return View();
}
Every way that I have tried it, html hidden and as a param in the begin form, doesn't work because it sees the #Model.ProjectId as null when it loads. As it should bc it is null. But how can I tell it to send it to the Create Tickets controller after the user selects and hits submit?
First Change This in your view
#Html.DropDownListFor(model => model.ProjectId, new SelectList(ViewBag.ProjectId , "Value", "Text"), "...", htmlAttributes: new { #class = "form-control" })
Change your controller variable name by ProjectId
It might Work fine
Another Way
You can add onclick in your button
function submitForm()
{
$.ajax(
{
url: 'Url',
type: "GET",
contentType: "application/json",
data: JSON.stringify({projId: $('ProjectId').val()}),
success: function(objStatus) {},
error: function(xhr, status, error)
{
if(status === "timeout")
{
alert(msg_timeout);
}
else
{
alert(msg_error);
}
},
});
}
why you set null the feeder argument of dropDownListFor ?
set with ViewBag.ProjectId content instead of null
Or
you can fill the viewbag with projects data and in view
do like this :
Controller
[AllowAnonymous]
public ActionResult NavRoleItems()
{
ViewBag.Projects = db.Projects;
return View();
}
View
add a model top of the page that it has ProjectId property
#Html.DropDownListFor(x => x.ProjectId, new SelectList(ViewBag.Projects, "Id", "Name"))
change Create action argument to type that insert top of the view

How to add form id using Sitecore or .NET

I am trying to add the id to a submit form and the codes are written using Sitecore:
#using (Html.BeginForm())
{
#Html.Sitecore().FormHandler("Payment", "Submit");
}
I have one controller called Payment Controller and uses the submit function inside of the controller. But now I want to add the id to the form, when I try:
#using (Html.BeginForm(null,null, FormMethod.Post, new { id = "FormFinalize" } ))
{
#Html.Sitecore().FormHandler("Payment", "Submit");
}
It looks like some function breaks.. Anyone has any idea how to correctly add the id to the form? Thanks.
You need # sing before the id or any other attribute you need to add like name,class and so on
#using (Html.BeginForm(null,null, FormMethod.Post, new { #id = "FormFinalize" } ))
{
#Html.Sitecore().FormHandler("Payment", "Submit");
}
I would suggest using this code:
#using (Html.BeginForm("Submit", "Payment", FormMethod.Post, new { id = "FormFinalize" } ))
{
<button type="submit">Submit</button>
}

Passing multi select values to controller in MVC5

so im trying to pass back the selected values in an array from this Kendo UI multi select
#(Html.Kendo().MultiSelect()
.Placeholder("Select Profiles")
.Name("Profiles")
.Value(new[] { new { } })
.HtmlAttributes(new
{
id = "ID",
data_bind = "options: Profiles_msl, optionsText: 'profiles', optionsValue: 'ID'"
})
)
controller method emty
public async Task<ActionResult> Regen(ViewModel model, string selcteditem )
{
if (ModelState.IsValid)
{
}
// If we got this far, something failed, redisplay form
return View(model);
}
and this is the form header on the cshtml page
#using (Html.BeginForm("Regen", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
This is currently saying that the object is null, Im just wanting to pass the array of selected values to the controller
any help would be good

Call post function when dropdown selected change in mvc4

I was Bind one dropdown with some values and call my post action when dropdown selected changed .for look like
#Html.DropDownListFor(m => m.DistrictId, Model.DistrictList, "Select", new
{
disableValidation = "true",
onchange = #"
var form = document.forms[0];
form.action='Index';
form.submit();"
})
This is working fine for call my controller post action . But I can't get dropdown selected value in my model DistrictId property .
For my controller function is look like below
[HttpPost]
public ActionResult Index(HomeModel homeModel)
{
AdminController adminController = new AdminController();
Guid userId = new Guid();
homeModel.ComplianceModelList = complianceRepository.LoadComplianceModel(userId, homeModel.DistrictId);
LoadDistrict(homeModel);
return View(homeModel);
}
I want to the dropdown selected DistrictId in my homeModel.DistrictId property .
How to do ?
Change your Markup like this
#Html.DropDownListFor(m => m.DistrictId, Model.DistrictList, "Select")
and have some javascript to handle your change event so that it will serialize your form and send it to your action method using ajax.
$(function(){
$("#DistrictId").change(function(e){
var _this=$(this);
$.post("#Url.Action("Index","Home")",_this.closest("form").serialize(),
function(response){
// do something with response.
});
});
});
Assuming you have jQuery library loaded to your page.
Now I got the solution
Below code was working good .
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<h2 class="gridTitle">
Compliance</h2>
if (User.Identity.IsAuthenticated && User.IsInRole("SuperAdmin"))
{
<div class="complianceSubDiv">
<div class="complianceRightDiv">
#Html.LabelFor(model => Model.DistrictId)
#Html.DropDownListFor(m => m.DistrictId, Model.DistrictList, "Select", new
{
disableValidation = "true",
onchange = #"
form.submit();"
})</div>
</div>
}
}

Categories

Resources