I am using Ajax,beginform to get partial postback, have install the Microsoft.jQuery.Unobtrusive.Ajax package, set up the bundle and added the keys in config files. With all this done when i click my submit button i get full postback. Have gone though tones of post and tried all suggested solutions, still seems to not work. is there anything i am still missing.
#using (Ajax.BeginForm("MyAction", "MyController", new AjaxOptions()
{
HttpMethod = "GET",
UpdateTargetId = "divList",
InsertionMode = InsertionMode.Replace
}))
{
<button type="submit"><span><span class="sr-only">Show more List</span></span></button>
}
<div id="divList">
#Html.Partial("_MyList.cshtml", Model.List)
</div>
In my controller
public ActionResult MyAction()
{
.....
return PartialView("_MyList", list);
}
Added in the bundle
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
In web.config
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Have even tried setting the section script in my view
#section Scripts {
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#Scripts.Render("~/bundles/jqueryval")
}
Another best way to handle the scenario is, instead of Ajax.BeginForm use Html.BeginForm
Use JQuery form submit, this will help you to stay away from jquery.unobtrusive
In .cshtml
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { id = "form_" + #Model.Id }))
{
<div>
#Html.HiddenFor(m => m.AntiForgeryToken, new { #class = "form-control" })
#Html.HiddenFor(m => m.Id, new { #class = "form-control" })
<button onclick='onClickFormButton("form_#Model.Id")' type="button">Submit</button>
</div>
}
Javascript
window.onClickFormButton = function (formId) {
//validate the form clientside
var validateResult = OnValidateForm(formId);
if (!validateResult) return false;
var form = $('#' + formId);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function (result) {
// process the result
processSuccessResult(result)
},
fail: function (result) {
// process the result
processFailResult(result)
}
});
return false;
}
Controller/Action
[HttpPost]
public JsonResult ActionName(FormCollection model)
{
// Get id
var idKey = model.AllKeys.FirstOrDefault(x => x.Contains("Id"));
var id = model[idKey];
return new ProcessedResult(id);
}
Related
I have #Ajax.ActionLink call by which I am trying to pass data to controller and refresh partial view. When I click on the link instead of passing the data to the controller, it is redirecting me to the previous page.
Ajax code:
#Ajax.ActionLink(#mainType.Descr, "GetChosenFaqSubCategory", "FAQ",
new { #TabCode = #mainType.TabCode },
new AjaxOptions
{
UpdateTargetId = "reloadFaq",
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
})
Controller:
[HttpPost]
public ActionResult GetChosenFaqSubCategory(string TapCode)
{
string pFilter = "WebFaqCategoryCd=" + TapCode;
code...
return PartialView("GlobalFAQ", List);
}
As bundles I am loading:
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/jqueryunobtr").Include(
"~/Scripts/jquery-3.6.0.min.js"));
bundles.Add(new ScriptBundle("~/bundles/ajax").Include(
"~/Scripts/MicrosoftAjax*",
"~/Scripts/MicrosoftMvcAjax*"));
In the Web.config unobtrusive is allowed:
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
#Ajax.ActionLink(#mainType.Descr, "GetChosenFaqSubCategory", "FAQ",
new { #TabCode = #mainType.TabCode },
new AjaxOptions
{
UpdateTargetId = "reloadFaq",
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
})
You have #TabCode here but it would try to look for #TabCode in your parameters. Try it with "TabCode = #mainType.TabCode"
For better readability it looks like you're using an int to identify the Tab that is selected. TabId would probably be better when looking at it without documentation.
I am trying to implement some save functionality via AJAX. I have a view with controls defined like below to be populated from the model:
#Html.LabelFor(model => model.mediaName, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.mediaName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.mediaName, "", new { #class = "text-danger" })
#Html.LabelFor(model => model.mediaName, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.mediaName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.mediaName, "", new { #class = "text-danger" })
When a user modifies the data and clicks the save button, the View is able to build up the new data from those controls and send it to the Controller (which simply saves the model to the db).
I am trying to do the same but via AJAX but I am having problems accessing an "already-built" model from the controls...
function saveDetails() {
var model = //HOW I GET THE MODEL?
$.ajax({
url: '/Media/SaveDetails',
dataType: 'html',
data: {
obj: model
},
success: function (data) {
}
});
}
Is there any way I can access that model? Or I should build it control-by-control?
EDIT: This is how I expect the controller to get the action:
(Medium is the entity used in the Model)
public ActionResult SaveDetails(DomainModel.Medium obj)
{
db.Entry(obj).State = EntityState.Modified;
db.SaveChanges();
return PartialView("_MediaModalDetails", obj);
}
Since the form works normally before adding the AJAX, presumably you have a <form> enclosing the input elements? If so, you can serialize that form. So, for example, let's say your form has id="myForm", then you can do something like this:
var model = $('#myForm').serialize();
#using (Ajax.BeginForm("SaveDetails", "Media", new AjaxOptions { HttpMethod = "POST", OnSuccess = "AfterEntry()", OnBegin="ValidateForm()"}, new { id = "myForm" }))
It does the same thing which you will get my writing an external
$.ajax({
url: '/Media/SaveDetails',
type: "POST",
data: {obj: $('#myForm').serialize() },
success: function (data) { AfterEntry(data) }
})
// no need of dataType:'html' as its json
Using the Ajax.BeginForm technique will also do server side property validation for model.mediaName which you have mentioned in the Data Annotations
for e.g.
[Required(ErrorMessage = "Media Name is required")]
public string mediaName{ get; set; }
Using ajax.BeginForm will show error with a message if mediaName is blank..
i.e. #Html.ValidationMessageFor will be fired
you will have to write extra long validation in jquery if you are trying to do the same but via external Ajax otherwise #Html.ValidationMessageFor won't be fired
I have been working with MVC for the past few days.
I have a problem in one of my pages, i.e I have a page where q user enters the required details and uploads a file. I have two buttons named Upload for Uploading File and Create for creating new profile.
My Problem
My problem is I don't want to reload the whole page when user clicks on upload button. I was thinking of using an webmethod for fileupload.
I don't know if what am I doing wrong here
Can any one correct me
This is my Webmethod in my controller named Create
Controller
[WebMethod]
public string FileUpload(HttpPostedFileBase file, BugModel model)
{
BugModel bug = null;
if (file != null && file.ContentLength > 0)
{
string path = "/Content/UploadedFiles/" + Path.GetFileName(file.FileName);
string savedFileName = Path.Combine(System.Web.HttpContext.Current.Server.MapPath ("~" +path));
file.SaveAs(savedFileName);
BugAttachment attachment = new BugAttachment();
attachment.FileName = "~" + path.ToString();
bug.ListFile.Add(attachment);
model = bug;
}
return "FileUploaded";
}
used a script to call the method
Javascript
<script type="text/javascript">
function UploadFile() {
$.ajax({
type:"Post",
url: "LogABug/FileUpload",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("File Uploaded")
},
error: function () {
ErrorMessage("Try Again");
}
});
}
</script>
can any one tell me how can I do this ...if this is the wrong method correct me the right one with the ideas please
You are uploading the file separately. Therefore you will need two actions:
public string Something(BugModel model) for the model.
public string FileUpload(HttpPostedFileBase file) for the file
Now, I would use jQuery Form Plugin for ajax submitting. Here is an example:
<script type="text/javascript">
$(function () {
$("#file-upload-form").submit(function () {
$(this).ajaxSubmit({
target: "#message",
cache: false
});
return false;
});
});
</script>
#using(Html.BeginForm("FileUpload", "LogABug", FormMethod.Post, new { enctype = "multipart/form-data", id = "file-upload-form" })) {
#Html.ValidationSummary(true)
<fieldset>
#Html.EditorFor(model => model.File)
<input type="submit" value="Upload" />
</fieldset>
}
<div id="message">
</div>
What ever you return from your action will be displayed in the div with id message
I have a certain ajax form and when submitted I want to include another form outside of that ajax form. Let me show you an example:
#using (Ajax.BeginForm("PayWithBankTransfer", "Payment", new { salesLineId = salesLine.SalesLineID }, new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "bankForm",
LoadingElementId = "spinnerBank"
}, new { id = "feedback-form" }))
{
//some stuff
<button type="submit">Reserve</button>
}
I have another tag outside of the form I want to include in the ajax form submission
<div id="theOtherStuff">
//otherStuff
</div>
How could I submit the other stuff along with the ajax form?
I don't think that MS unobtrusive AJAX supports this. So let's get rid of it and use plain jQuery. The .serialize() method is what you are looking for.
So we start by replacing the Ajax.BeginForm form with a regular Html.BeginForm
#using (Html.BeginForm(
"PayWithBankTransfer",
"Payment",
new { salesLineId = salesLine.SalesLineID },
FormMethod.Post,
new { id = "feedback-form" })
)
{
//some stuff
<button type="submit" class="t-button t-state-default" style="width: 100px; height: 50px;">Reserver</button>
}
then we provide an id to the other form so that we can reference it in our script:
<div id="theOtherStuff">
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "theOtherStuffForm" }))
{
//otherStuff
}
</div>
and all that's left is write our script in a separate javascript file to unobtrusively AJAXify this form:
$(function() {
$('#feedback-form').submit(function () {
$('#spinnerBank').show();
$.ajax({
url: this.action,
type: this.method,
data: $(this).add('#theOtherStuffForm').serialize(),
success: function (result) {
$('#bankForm').html(result);
},
complete: function () {
$('#spinnerBank').hide();
}
});
return false;
});
});
The following line should be of particular interest:
data: $(this).add('#theOtherStuffForm').serialize(),
As you can see the .serialize method allows convert multiple forms into suitable serialized form.
It is more than obvious that you should not have conflicting names with the input elements of the 2 forms (for example have 2 elements with the same name), otherwise the default model binder could go berserk. It's up to you to resolve those conflicts if there are any.
I would like to make POST request using following code
<div class="editor-field" id="updateDiv" >
#Html.EditorFor(model => model.UserName)
#Html.ValidationMessageFor(model => model.UserName)
</div>
<div>
#Ajax.ActionLink("Check Availability", "ValidateUsername", "Wizard",
new { username = "username"},
new AjaxOptions() {
UpdateTargetId = "msg",
HttpMethod = "POST",
LoadingElementId = "progress",
}
)
</div>
But instead of passing a static value I want to pass value of #Html.EditorFor(model => model.UserName) (user inputed value), how can I do this?
First, it seems you're trying to create some kind of remote validation. This mechanism is already in place in MVC so you can use it with DataAnnotations
http://msdn.microsoft.com/en-us/library/gg508808(v=vs.98).aspx
If I'm wrong with my assumption, you can try to modify your code according to the below.
I would go with adding htmlAttributes to set id for the link like this :
#Ajax.ActionLink("Check Availability", "ValidateUsername", "Wizard",
new {username = "username"},
new AjaxOptions()
{
UpdateTargetId = "msg",
HttpMethod = "POST",
LoadingElementId = "progress",
}, new { id = "CheckAvailabilityLink" }
)
having that in place we have a direct reference to this element so we can track changes on the textbox and update URL dynamically
<script type="text/javascript">
$(document).ready(function () {
$("#UserName").keyup(function (e) { // textbox id here
var href = $("#CheckAvailabilityLink").attr("href").split("?", 1);
$("#CheckAvailabilityLink").attr("href", href + "?username=" + $(this).val());
alert($("#CheckAvailabilityLink").attr("href"));
});
});
</script>
</script>