Call post function when dropdown selected change in mvc4 - c#

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>
}
}

Related

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 make a script refresh and redirecting for Ajax.BeginForm MVC

I created a form using Ajax.BeginForm
#using (Ajax.BeginForm("CreatePlayer", "Admin", null, new AjaxOptions() { HttpMethod = "post" }))
{
<div class="row">
<div class="col-md-6">
<div class="text-style-roboto form-group">
<label>Имя</label>
#Html.TextBoxFor(x => x.Name, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Name)
</div>
<div class="form-group">
<button type="submit" class="button button-create">Добавить</button>
</div>
</div>
</div>
}
When I push the button to make a new player, a player is created but the form stays filled.
,
The desired behaviour is that the form should be cleared, but it doesn't. I don't how to clear the form using jQuery. Should I refresh the page, or some other way.
My post action in controller is -
[HttpPost]
public JsonResult CreatePlayer(CreatePlayerModel model, string TeamNameId)
{
if (ModelState.IsValid)
{
if (TeamNameId != string.Empty)
{
try
{
int newTeamId = int.Parse(TeamNameId);
repository.CreatePlayer(model, newTeamId);
TempData["message"] = string.Format("Игрок {0} {1} сохранены", model.Name, model.Surname);
return new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new { result = "success" }
};
}
catch (Exception exc)
{
Console.WriteLine(exc.Message);
}
}
}
IEnumerable<SelectListItem> list = new SelectList(repository.Teams, "Id ", "Name");
ViewBag.ChoosingTeam = list;
return new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new { result = "error" }
};
}
If it's needed, I can do the action by html forms to Ajax.
If you are using AJAX, the form would not be cleared automatically and you need to clear it. You can set values of input text and textareas to ''. Also, you need to reset the values of selects.
Assuming that the form id is CreatePlayer then to set the values of input text and textarea to blank ('') -
$('#CreatePlayer').find("input[type=text], textarea").val('');
Similarly, you can set the value of select to default value of your choice. Assuming that the select to be reset by the first option and the id of select is teamSel, then to reset the value -
$("#teamSel").val($("#teamSel option:first").val());
If you have a reset button added in the form, you can trigger the reset but that won't set the default values to form inputs. To trigger the reset -
$("#CreatePlayer").trigger('reset');
__ UPDATE ___
You should be calling these(depending on your requirement), in OnSuccess and/or OnFailure.
You should clear the form when AJAX call returns with success. That said, inside OnSuccess, clear the form.
You should show errors if OnFailure is called.

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

Pass values from view, as input values to form in ASP.NET MVC

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!

How to change labels of a form with json and razor snytax in .Net MVC3

I'm trying to use json for my web page's globalization options.. id like to change the labels of my form just by using a little dropdownbox and without refreshing the whole page and more interesting part is i got more than two form in my view.
so far i have done this:
My Json:
public JsonResult Globalx(String incoming)
{
System.Globalization.CultureInfo Cult = new System.Globalization.CultureInfo(incoming, true);
System.Threading.Thread.CurrentThread.CurrentCulture = Cult;
System.Threading.Thread.CurrentThread.CurrentUICulture = Cult;
Resources.Global.Culture = System.Threading.Thread.CurrentThread.CurrentCulture;
Global.ResourceManager.GetResourceSet(Cult, false, true);
ViewData["Name"] = Global.Name;
ViewData["Surname"] = Global.Surname;
ViewData["Birth"] = Global.Birth;
String lnginfo = Resources.Global.Culture.TwoLetterISOLanguageName.ToString();
ViewData["Languages"] = new SelectList(myList, "Value", "Text", lnginfo);
return Json(ViewData, JsonRequestBehavior.AllowGet);
}
My View:
#model MyCustomers.Models.Customers
#{
ViewBag.Title = ViewData["NewCustomer"];
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript" language="javascript">
$(document).ready(function () {
function changeLang() {
var lang = $("#LanguageBox").val();
$.getJSON('#Url.Content("~/Home/People/")', { incoming: lang }, function (data) {
// what should i do here to get my label's language changed?
})
}
}
</script>
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "LanguageForm" }))
{
<fieldset>
<legend>#ViewData["LanguagesTitle"]</legend>
#Html.DropDownListFor(x => x.SelectedLanguage, (SelectList)ViewData["Languages"], new { onchange = "changeLang()", id = "LanguageBox" })
</fieldset>
}
#using (Html.BeginForm("PeopleForm", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "PeopleForm" }))
{
<fieldset>
<legend>#ViewData["SalesContract"]</legend>
<div>
<div class="Name">
#Html.Label(ViewData["Name"].ToString()) <!--> HERE </!-->
#Html.EditorFor(x => x.People.Name)
</div>
<div class="Surname">
#Html.Label(ViewData["Surname"].ToString()) <!--> HERE </!-->
#Html.EditorFor(x => x.People.Surname)
</div>
<div class="Birth">
#Html.Label(ViewData["Birth"].ToString()) <!--> AND HERE </!-->
#Html.EditorFor(x => x.People.Birth)
</div>
</div>
</fieldset>
}
No im not actually using this method im refreshing the whole page each time to change the language of my labels but some friend of mine told me it could be done without refreshing and the first thing that came in my mind was Json.. I dont know if its possible or not im just trying. Any other ideas are wellcome.
I think the title is a little confusing and im asuming my problem here is understood so if anyone can find a better title please attempt to fix it.
In your Json result you would need to identify each of the labels that you have provided the text for, say each label has a Json object:
Id: 'label1',
Text: 'Enter your first name'
You provide one of these objects for each label on your page in an array,
{Id: 'label1', Text: 'Enter your first name'},
{Id: 'label2', Text: 'Enter your second name'},
{Id: 'label3', Text: 'Enter your telephone number'},
Then you deal with each of these on the requesting end,
$.getJSON('#Url.Content("~/Home/People/")', { incoming: lang }, function (data) {
for(i = 0; i < data.length; i++){
$('#'+data[i].Id).Html(data[i].Text);
}
})
I'm not 100% sure that Html will be the best thing to use - there may be sub DOM elements created by MVC that would need to be taken into account in your selector.
If you wanted to stick to the method you're using now you'll need to hard code each of the assigned values one at a time.
$.getJSON('#Url.Content("~/Home/People/")', { incoming: lang }, function (data) {
$('#Name').Html(data['Name']);
$('#Birth').Html(data['Birth']);
})

Categories

Resources