ASP.NET MVC Multi-language feature does not work as expected - asp.net-mvc

I have the app working using Radio buttons e.g.
#using (Html.BeginForm("SetCulture", "Home"))
{
<input type="radio" name="culture" id="en-us" value="en-us" class="culture" /> English
<input type="radio" name="culture" id="tr" value="tr" class="culture" /> Türk
}
but when i use input of image type it does not send the wanted VALUE
#using (Html.BeginForm("SetCulture", "Home"))
{
<input type="image" src="~/Content/Images/en.png" name="culture" id="en-us" value="en-us" class="culture" />
<input type="image" src="~/Content/Images/tr.png" name="culture" id="tr" value="tr" class="culture" />
}
jQuery code:
$(".culture").click(function () {
$(this).parents("form").submit(); // post form
});
HomeController Code:
public ActionResult SetCulture(string culture){
// action code here
}
I see no reason why the images wouldn't work but for some reason it happens. Any ideas?
Thank you so much

In the first code block (using <input type="radio" .. />), you form will only post back one value for culture (the value of the selected radio button).
In the second code block (using <input type="image" .. />) your form will post back the values of both inputs, so your form data is culture=en-US&culture=tr
The DefaultModelBinder will bind the first value and ignore the second value so the value of culture in the POST method will always be "en-US" irrespective of which image you click.
One option would be to disable the other input (disabled inputs do not post back a value, for example
$(".culture").click(function () {
$(this).siblings().prop('disabled', true); // disable the other input
$(this).parents("form").submit(); // post form
});
Another option for handling this is to use <img> tags in conjunction with a hidden input for the culture value
<input type="hidden" name="culture" id="culture"/>
<img src="~/Content/Images/en.png" data-culture="en-US" class="culture" />
<img src="~/Content/Images/tr.png" data-culture="tr" class="culture" />
$('.culture').click(function () {
$('#culture').val($(this).data('culture')); // update the hidden input
$('form').submit();
})

Related

Can't route my input parameters to my controller action method

I'm having trouble passing my textbox data to a controllers action parameters.
I'm trying to get the url to look like:
http://localhost:51124/gifts?searchTerm=test
but when I enter in text into the text box I get a url that looks like:
http://localhost:51124/gifts
Here is the code I have for the route:
routes.MapRoute("Gifts",
"gifts",
new { controller = "Gifts", action = "Search" });
here is the code for the page with the text box and button to submit the text box data:
<form method="GET">
<input type="search" name="searchTerm"/>
<input type="button" value="Search By Category" onclick="location.href='#Url.Action("Search", "Gifts")'" />
</form>
here is the code for the controller that I'm trying to pass data to unsuccessfully:
public ActionResult Search(string searchTerm = null)
{
var model = db.Gifts.ToList();
return View(model);
}
"searchTerm" never gets any parameter that I pass into the text box. It's always null.
Create a form element in you view with an input (i.e. the search box) that has a name attribute matching the parameter and a submit button.
#using (Html.BeginForm("Search", "Gifts") {
<input type='text' name='searchTerm' value='' />
<input type='submit' value='search' />
}
This will post back to the Search method in the Gifts controller, passing the vale of the search box to the parameter 'searchTerm'
you have to build this with jquery. add a class to the inputs to use as a selector
<input type="search" name="searchTerm" class="txtSearch" />
<input type="button" value="Search By Category" class="btnSearch" />
then in your script
$('.btnSearch').on('click', function(){
var url = '#Url.Action("Search", "Gifts", new { searchTerm = "----" })'.replace("----", $('.txtSearch').val());
window.location(url);
});

Checking & Unchecking Checkboxes inside a JQuery Mobile Dialog

I tried this code to achieve what I want to do. It worked when I tried it in my ordinary HTML file, but when I tried it in my JQuery Mobile page, the code did not work well for me. Are there different ways or code to select JQuery Mobile checkboxes?
Here's the code that I tried:
JAVASCRIPT:
<script>
function SetAllCheckBoxes(FormName, FieldName, CheckValue)
{
if(!document.forms[FormName])
return;
var objCheckBoxes = document.forms[FormName].elements[FieldName];
if(!objCheckBoxes)
return;
var countCheckBoxes = objCheckBoxes.length;
if(!countCheckBoxes)
objCheckBoxes.checked = CheckValue;
else
// set the check value for all check boxes
for(var i = 0; i < countCheckBoxes; i++)
objCheckBoxes[i].checked = CheckValue;
}
HTML
<form method="GET" name="myForm" onsubmit="return false;">
<label for="myCheckbox1">
<input type="checkbox" name="myCheckbox" value="1" id="myCheckbox1">
I like Britney Spears
</label>
<br>
<label for="myCheckbox2"><input type="checkbox" name="myCheckbox" value="2" id="myCheckbox2">
I like Hillary Duff
</label>
<br>
<label for="myCheckbox3"><input type="checkbox" name="myCheckbox" value="3" id="myCheckbox3">
I like Mandy Moore
</label>
<br>
<input type="button" onclick="SetAllCheckBoxes('myForm', 'myCheckbox', true);" value="I like them all!">
<input type="button" onclick="SetAllCheckBoxes('myForm', 'myCheckbox', false);" value="I don't like any of them!">
I was not aware that JQuery Mobile's checkboxes need to be refreshed after unchecking/checking them via JQuery or Javascript. Here's the code:
$("input[type='checkbox']").attr("checked",true).checkboxradio("refresh");
http://api.jquerymobile.com/checkboxradio/#method-refresh
Try this:
function SetAllCheckBoxes(FormName, CheckValue){
$.each($("#"+FormName+" input[type=checkbox]"), function(){
$(this).attr("checked",CheckValue).checkboxradio("refresh");
});
}
I removed the FieldName because your function was named SetAllCheckBoxes, just your input fields are the same. You just need tell what's your form and the state of your checkboxes.
To toggle / refresh checkboxes in jquery mobile you need to use .prop, rather than .attr.
$("input[type='checkbox']").prop("checked",true).checkboxradio("refresh");

how to post form in MVC 3.0 razor on radio button change

I want to active and inactive user account on click on form post. I am using
#using (Ajax.BeginForm("SetStatus", "Home", null, new AjaxOptions() { HttpMethod = "Post" }, null))
{
if (res.Status == 1)
{
<span class="userStatusSpan statusActive"><input type="radio" name="status" value="1" checked="checked" />Active</span>
<span class="userStatusSpan statusInactive"><input type="radio" name="status" value="0" />Inactive</span>
}
else
{
<span class="userStatusSpan statusActive"><input type="radio" name="status" value="1" />Active</span>
<span class="userStatusSpan statusInactive"><input type="radio" name="status" checked="checked" value="0" />Inactive</span>
}
}
Can anyone please tell me how to post form on check box change?
You can call below javascript function onclick event of your radio button.
<script type="text/javascript">
function submitform()
{
document.myform.submit();
}
</script>
In my opinion in this case better to use plain jQuery ajax post. Some example you can find here: Submit form when checkbox is checked - tutorial
Just go for document.formid.submit();

How redirect action with all params

I have action in controller Statistic
public ViewResult Index(string userName, GridSortOptions gridSortOptions, int? page, DateTime? dateTimeFrom, DateTime? dateTimeTo)
{
..
}
I create partial view _FromToDateViewPage.cshtml
<script language="javascript">
$(function () {
$("#datepickerFrom").datepicker();
$("#datepickerTo").datepicker();
});
</script>
<div class="date_box">
<p><span>Date From: <input type="text" id="datepickerFrom"></span><span>Date To: <input type="text" id="datepickerTo"></span></p>
#Html.RouteLink("Filter", new { Controller = ViewContext.Controller.ValueProvider.GetValue("controller").RawValue, Action = ViewContext.Controller.ValueProvider.GetValue("action").RawValue, dateTimeFrom = DateTime.Now })
</div><!-- Date (From To) Picker Box -->
I need a filter button that sends the current effect that all options were. And + dateTimeFrom and dateTimeTo
In your view you have to use a submit button and not a link.
<form>
<input type="hidden" name="page" value="#ViewBag.page">
<input type="hidden" name="username" value="#ViewBag.username">
<!-- deserialize the gridSortOptions -->
<input type="hidden" name="gridSortOptions_field" value="#ViewBag.gridSortOptions_field">
<input type="hidden" name="gridSortOptions_field" value="#ViewBag.gridSortOptions_direction">
<!-- add the value attribute and set it's value to datepickerFrom stored in viewBag -->
Date From: <input type="text" id="datepickerFrom" name="datepickerFrom" value="#ViewBag.datepickerFrom">
<!-- add the value attribute and set it's value to datepickerTostored in viewBag -->
Date To: <input type="text" id="datepickerTo" name="datepickerTo" value="#ViewBag.datepickerTo">
<input type="submit">
</form>

Multiple forms in ASP.NET MVC

Context
Let`s say i have:
In layout Site.Master:
<div class="leftColumn">
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
</div>
<div class="rightColumn">
<% Html.RenderPartial("_Login"); %>
<asp:ContentPlaceHolder ID="SideContent" runat="server" />
</div>
Login partialView looks like:
<form action="/myApp/Account/Login" method="post">
<input name="name" />Name<br />
<input name="password" type="password" />Password<br />
<button>Login</button>
</form>
Is it possible to update only login widget form, not the entire content page?
If you are referring to a http post, only a post initiated (it can also be initiated by javascript) by a submit button from within the form will be posted to the server.
If your forms are nested then this won't work. The outer form will always post to the server.
In the sample HTML below, clicking on the submit button on the first form will not send the values from the second form to the server. Likewise, clicking the second submit button won't post the values from the first form.
<html>
...
<body>
<div>
<form action="/Login/Login" method="post">
<input type="text" name="username" value="" />
<input type="text" name="passowrd" value="" />
<input type="submit" name="login" value="Login" />
</form>
<form action="/Login/AdminLogin" method="post">
<input type="text" name="username" value="" />
<input type="text" name="passowrd" value="" />
<input type="submit" name="login" value="Login Admin" />
</form>
</div>
</body>
</html>
If you only wish to update/change one of the form section, then no this can not be done without using javascript and performing a javascript post(aka Ajax).
If you build a controller method that accepts a FormCollection and your view has two forms defined, the formcollection returned will either be populated with values from form A or form B. You can inspect the formCollection and branch your logic based on the value therein. If you want the be very explicit you could have the same hidden variable occur in both forms with a value that would help your make your choice.
That's one approach. there are a few ways to deal with this I'm sure.
If you have two simple forms, you can use this aproach:
You create two different partial views.
#model CustomerInfoModel
#using (Ajax.BeginForm("CustomerInfo", "Customer", new AjaxOptions { HttpMethod = "Post", OnBegin = "InfoLoading", OnComplete = "InfoCompleted" }, new { id = "info", #class = "form-horizontal" }))
{
<input type="text" class="form-control" name="Name" id="Name" value="#Model.Name" />
<input type="email" class="form-control" name="Email" id="Email" value="#Model.Email" />
<button type="submit" id="save-info" class="btn-medium red">Save</button>
}
and
#model CustomerPasswordChangeModel
#using (Ajax.BeginForm("CustomerPasswordChange", "Customer", new AjaxOptions { HttpMethod = "Post", OnBegin = "InfoLoading", OnComplete = "InfoCompleted" }, new { id = "change", #class = "form-horizontal" }))
{
<input type="password" class="form-control" name="OldPassword" id="OldPassword" value="" />
<input type="password" class="form-control" name="NewPassword" id="NewPassword" value="" />
<button type="submit" id="save-change" class="btn-medium red" autocomplete="off">Save</button>
}
In your parent view,
#Html.Partial("CustomerInfo", Model.CustomerInfo)
and
#Html.Partial("CustomerPasswordChange", Model.CustomerPasswordChange)
In Controller:
[HttpPost]
public ActionResult CustomerInfo([Bind(Include = "Name,Email")] CustomerInfoModel model)
{
if (ModelState.IsValid)
return new Json(new { success=true, message="Updated.", errors=null);
// do you logic
return new Json(new { success=false, message="", errors=getHtmlContent(ModelState.Values.SelectMany(v => v.Errors).ToList(), "ModelError"));
}
[HttpPost]
public ActionResult CustomerPasswordChange([Bind(Include = "OldPassword,NewPassword")] CustomerPasswordChangeModel model)
{
if (ModelState.IsValid)
return new Json(new { success=true, message="Updated.", errors=null);
// do you logic
return new Json(new { success=false, message="", errors=getHtmlContent(ModelState.Values.SelectMany(v => v.Errors).ToList(), "ModelError"));
}
This will do what you want to do.
Note: getHtmlContent method is just generating an error message to be displayed on page. Nothing so special. I may share it if required.
Your question is not very clear.
But as far as I could understand, the answer is most likely yes. You can update anything you want depending on the user input.
if(pass != true)
{
ViewData["Message'] = "Hey your login failed!"; Return View("Login")
}
On ViewPage
<form action="/tralala/Account/Login" method="post">
<input name="name" />Name<br />
<input name="password" type="password" />Password<br />
<button>Login</button>
<div style="color: red"><%=ViewData["Message"] %><div>
</form>

Resources