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
Related
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
#Html.ActionLink((string)Model[i]["name"], "Info", "Home", new { uid = Model[i]["uid"].ToString() }, null)
[HttpGet]
public ActionResult Info(string uid)
{
TempData["uid"] = uid;
SearchModel model = new SearchModel();
List<DataTable> tables = model.GetUserInfo(uid);
TempData["tables"] = tables;
return View(model);
}
In the controller, there is a method that returns JsonResult. This method is used to obtain data, on the basis of which the js code will be executed.
public JsonResult GetCountryRisk(SearchModel model)
{
string uid = TempData["uid"].ToString();
IEnumerable<CountryRisk> list = new List<CountryRisk>();
list = model.GetCountryRisk(uid);
TempData["uid"] = uid;
return Json(list, JsonRequestBehavior.AllowGet);
}
The view has elements that simulate tabs and when clicked on the selected item, Ajax is called, which receives the data and passes it to the script.
<div id="tabHeadDiv">
<input type="button" value="Summary" class="tabControl" id="1" onclick="ShowOrHideTabs(this.id)" />
#Ajax.ActionLink("Relations", "Info", null, new AjaxOptions { Url = Url.Action("GetDataForGraph"), OnSuccess = "DrawGraph" }, new { #id = "2", #class = "tabControl" })
#Ajax.ActionLink("Map", "Info", null, new AjaxOptions { Url = Url.Action("GetCountryRisk"), OnSuccess = "drawRegionsMap" }, new { #id = "3", #class = "tabControl" })
</div>
Problem is that if a user opens several links in a new tab and wants to go to the tab, then on all tabs the result will be displayed, which was executed last.
So I want to understand if it's possible to send parameter to the GetCountryRisk method without using TempData ["uid"].
First, stop using a ViewBag or a TempData for uid. This is clearly a part of your state, and while these key-value stores have their uses, they are no good for your case.
Make uid a part of SearchModel, as it is obviously important for you as you handle search requests, and in Info action do this:
SearchModel model = new SearchModel();
model.UID = uid;
Now on the page I don't really understand why the Ajax.ActionLink mentions one controller/action pair and then uses another as the URL. Here is how I would imagine it:
#Ajax.ActionLink(
"Your controller name",
"GetCountryRisk",
new {uid = Model.UID},
new AjaxOptions {OnSuccess = "drawRegionsMap" },
new { #id = "3", #class = "tabControl" })
Finally in the GetCountryRisk action just use uid:
public JsonResult GetCountryRisk(SearchModel model)
{
string uid = model.UID;
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
I have a view which calls a child action:
#Html.Action("RenderPostMessage", "JobSurface")
The controller is like this:
public ActionResult RenderPostMessage()
{
PostMessageViewModel postMessageViewModel = new PostMessageViewModel();
return PartialView("PostMessage", postMessageViewModel);
}
The partial this calls is like this:
#model PostMessageViewModel
#{
Html.EnableClientValidation(true);
Html.EnableUnobtrusiveJavaScript(true);
}
#using (Html.BeginUmbracoForm<JobSurfaceController>("HandlePostMessage", new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<p>
#Html.EditorFor(model => model.Message)
#Html.ValidationMessageFor(model => model.Message)
</p>
<p>
#Html.LabelFor(model => model.File)
#Html.TextBoxFor(x => x.File, new { type = "file" })
</p>
<p><button class="button">Post Message</button></p>
}
The 'handle post message' controller is like this:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult HandlePostMessage(PostMessageViewModel model)
{
// Some logic
}
I have a bunch of variables in the view that I need to somehow pass in to the form (as hidden input fields perhaps?) but although I know how to create hidden inputs on the partial, I've no idea how to populate them with the values from the view.
Could anyone suggest how to get the value passed through to the controller?
Many thanks.
I have a bunch of variables in the view that I need to somehow pass in
to the form (as hidden input fields perhaps?)
It's simple, if you want to render a hidden input field with a value then add it to the ViewBag object in the view.
For instance, if you want to add the content of a variable to the form then in the view you do this:
ViewBag.Foo = "Some Value";
Then in the cshtml file you add the hidden field:
#Html.Hidden("Foo")
This way you will receive the value in the form post.
EDIT: this is how your code should look.
public ActionResult RenderPostMessage()
{
PostMessageViewModel postMessageViewModel = new PostMessageViewModel();
// here you set as many values as you want to receive in the form post.
ViewBag.SomeField = "Some Value";
return PartialView("PostMessage", postMessageViewModel);
}
View
#model PostMessageViewModel
#{
Html.EnableClientValidation(true);
Html.EnableUnobtrusiveJavaScript(true);
}
#using (Html.BeginUmbracoForm<JobSurfaceController>("HandlePostMessage", new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.Hidden("SomeField")
<p>
#Html.EditorFor(model => model.Message)
#Html.ValidationMessageFor(model => model.Message)
</p>
<p>
#Html.LabelFor(model => model.File)
#Html.TextBoxFor(x => x.File, new { type = "file" })
</p>
<p><button class="button">Post Message</button></p>
}
#Html.Action has a parameter 'routeValues' which is an anonymous object. You can pass values there. So...from view to action:
#Html.Action("RenderPostMessage", routeValues:new{SurfaceType = "JobSurface", OtherValue = "Something", NewValue = "Something else"});
Action accepts these route values as method parameters:
public ActionResult RenderPostMessage(string surfaceType, string otherValue, string newValue)
{
var viewModel = new PostMessageViewModel();
viewModel.SurfaceType = surfaceType;
viewModel.OtherValue = otherValue;
viewModel.NewValue = newValue;
return PartialView("PostMessage", viewModel);
}
Done!
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>
}
}