Example:
<div id="result"> some action </div>
#Ajax.ActionLink("Vote", "vote", new { id = Model.Catalog_Id, vote = result }, new AjaxOptions { HttpMethod = "POST", OnSuccess = "location = location", Confirm = "Are you sure to vote?" })
Div result will change immediately when user selects a different radio button value. I want to pass latest radio button value to controller to insert data. Is that possible?
Using ajax method call can solve the problem
Related
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.
I am using Ajax begin form for a search page to bring back results. I have the following markup.
#using (Ajax.BeginForm("GetSearchResults",
"MYController",
new
{
siteID = Model.SiteID
},
new AjaxOptions()
{
HttpMethod = "GET",
AllowCache = true,
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "search-reults"
}))
{
#Html_DropDownListFor(model => model.SiteID, Model.StatusCollection)
}
There are a few other strong type textboxes and a submit button on the page. All textboxes submit data back to the controller but the drop down list doesn't. It always submits the default value 0. Are there any other steps I need to do to pick up the value or something in the JQuery onchange event?
Removing the route parameter siteID worked. I do not need to pass strong type control values through as route parameters.
I'm creating a form for a DropDown like this:
#{
Html.BeginForm("View", "Stations", FormMethod.Get);
}
#Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"), new { onchange = "this.form.submit();" })
#{
Html.EndForm();
}
If I choose a value from my dropdown I get redirected to the correct controller but the URL is not as I would like to have it:
/Stations/View?id=f2cecc62-7c8c-498d-b6b6-60d48a862c1c
What I want is:
/Stations/View/f2cecc62-7c8c-498d-b6b6-60d48a862c1c
So how do I get the id= querystring parameter replaced by the more simple URL Scheme I want?
A form with FormMethod.Get will always post back the values of its form controls as query string values. A browser cannot generate a url based on your route configurations because they are server side code.
If you really wanted to generate /Stations/View/f2cecc62-7c8c-498d-b6b6-60d48a862c1c, then you could use javascript/jquery to build your own url and redirect
#using (Html.BeginForm("View", "Stations", FormMethod.Get))
{
#Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"))
}
var baseUrl = '#Url.Action("View", "Stations")';
$('#id').change(function() {
location.href = baseUrl + '/' $(this).val();
});
Side note: Submitting on the .change() event is not expected behavior and is confusing to a user. Recommend you add a button to let the user make their selection, check it and then submit the form (handle the button's .click() event rather that the dropdownlist's .change() event)
Remove "id"
from
#Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"), new { onchange = "this.form.submit();" })
I have the following code in my View,
It's for searching in a site, a user can submit the following form multiple times.
#using (Ajax.BeginRouteForm("Search", new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "SearchContents",
LoadingElementId = "SearchAjaxLoader",
OnSuccess = "SearchLoadContentsOnSuccess",
OnFailure = "SearchLoadContentsOnFailure",
OnBegin = "SearchLoadContentsOnBegin",
OnComplete = "SearchLoadContentsOnComplete",
}))
{
#Html.AntiForgeryToken()
<input type="text" name="Search" />
<input type="submit" value="Submit" />
}
I wanna reject old ajax results and show the latest ajax result only.
In a non mvc Ajax form, I was creating an array as ajax counter and compare the server responses with it to prevent update html.
I wanna know how I can prevent Ajax.BeginForm to update Html on some conditions.
As an example I will demonstrate with an OnSuccess call, you can do this for each event you wish to handle.
In your AjaxOptions remove this to prevent the replace;
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "SearchContents",
In you SearchLoadContentsOnSuccess JavaScript method, without seeing the method I am guesing it will be something like this:
function SearchLoadContentsOnSuccess()
{
// Do something
}
Change it to this:
function SearchLoadContentsOnSuccess(e)
{
// Do something
}
Now the e parameter will contain the data that is sent back from your ajax call.
In your updated method, I would simply check the response and act acordingly.
As an example if you response contains a value and results property:
function SearchLoadContentsOnSuccess(e)
{
// Do something
$(e.value == 1)
{
$('#SearchContents').html(e.results);
}
}
You would simply change the javascript in the above method to suite your needs.
I have a code block in my MVC view as follows:
<%using (Ajax.BeginForm("MyAction", new { action = "MyAction", controller = "Home", id = ViewData["selected"].ToString() }, new AjaxOptions { UpdateTargetId = "Div1" }))
{ %>
<%=Html.DropDownList("ddl", ViewData["MyList"] as SelectList, new { onchange = "this.form.submit()" })%>
<%} %>
I want to set the value of ViewData["selected"] so that i can send it to the desired action.
Can anyone please suggest how can i do this?
thanks!
Instead of using a form, why not use a jQuery onChange event on your drop down?
$(document).ready(function() {
$("#ddl").change(function() {
var strSelected = "";
$("#ddl option:selected").each(function() {
strSelected += $(this)[0].value;
});
var url = "/Home/MyAction/" + strSelected;
$.post(url, function(data) {
// do something if necessary
});
});
});
ViewData is not the place to pass data back to the server side. Values of html input controls within form tag are conveniently available in action method. You can get these values either from various types of action method arguments (model, formcollection etc).
Here is a link to free asp.net mvc ebook tutorial. Is a good resource for asp.net mvc.
Found solution at this post it is just small chnge
Yes, that’s right – only change is replacing:
onchange = “this.form.submit();”
with:
onchange = “$(this.form).submit();”