Passing hidden value to controller (asp.netmvc) - ajax

Trying to pass a value with Ajax.Beginform but not working for some reason.
What I’m doing:
I’m making an ajax call which returns an id and replaces a hidden element.
Ajax: Ajax.BeginForm("Action1", "Controller1", new AjaxOptions { InsertionMode
= InsertionMode.Replace, UpdateTargetId = "pageId" })
Hidden Element (which is outside of the above Ajax.BeginForm):
<input type="hidden" name="pageId" id="pageId" value=""/>
Now, I want to use that pageId (in the hidden value) and pass it to another action, using another Ajax.BeginForm.
Ajax.BeginForm("Action2", "Controller1”))
{
<input type="hidden" name="pageId" id="pageId" value=""/>
<input type="submit" />
}
The controller Action2 looks like this:
public void Action2(string pageId)
{
}
But this is not working obviously. What are your suggestions?

I think that i understand your problem what you are facing. Please correct me if i am wrong.
First Ajax call which will set your pageid
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
#using (Ajax.BeginForm("Foo", "FooController", new AjaxOptions {
HttpMethod = "Post",
OnSuccess = "success"
}))
{
<input type="submit" value="Save" id="btnsubmit" />
}
[HttpPost] // you said you return a string here
public string Foo()
{
return "1";
}
<script type="text/javascript">
function success(result) {
$('#pageId').val(result);
}
</script>
secondly here is the place where your pageid will be set. when you will press the submit button below the set value will be posted to the controller.
#using (Ajax.BeginForm("Foo1", "FooController", new AjaxOptions { OnSuccess = "HandlePostback" }))
{
<input type="hidden" name="pageId" id="pageId" />
<input type="submit" value="Save" id="btnsubmit" />
}
[HttpPost]
public ActionResult Foo1(int pageId)
{
return View();
}

Related

Load/Refresh only part of a page (View) using AJAX in ASP.NET MVC

I am trying to achieve the same result as mentioned by the OP in this post However when I try to render partial view by checking if it was an AJAX request in my Index action, its evaluating to false.
My Index View:
#using (Ajax.BeginForm("Index", "Home",
new AjaxOptions()
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "restaurantList"
}))
{
<input type="search" name="searchTerm" />
<input type="submit" value="Search By Name" />
}
#Html.Partial("_Restaurant",Model)
My Partial View:
<div id="restaurantList" style="border:2px dotted red; padding-left:2em; margin-top:4px;">
#foreach (var item in Model)
{
<div>
<h4>#item.Name</h4>
<div>#item.City, #item.Country</div>
<div>#item.CountOfReviews</div>
<hr />
</div>
}
</div>
My Index Action:
public ActionResult Index(string searchTerm = null)
{
var model = ...//Building model object here
if (Request.IsAjaxRequest())
{
return PartialView("_Restaurant", model);
}
return View(model);
I would prefer not to dive into use of any jQuery or javascript as I am in the process of learning ASP.NET MVC, and would want to know why the approach I took is not working? The second answer by Dennis, in the post that I referenced also suggested similar approach.
Could someone kindly tell me what I am doing wrong?
Thanks
This is just an example how you can load view from AJAX without page refresh, it may help you.
It send text value to controller by ajax call and load that value in other view which replace main view, if you don't want to replace main view then you can take other div instead same div to load content.
Controller:
public ActionResult Index()
{
return View();
}
[HttpPost]
public PartialViewResult TestAjax(string Name)
{
ViewBag.Name = Name;
return PartialView();
}
Index.cshtml:
<input type="button" id="btnSearch" class="btn btn-warning" style="height:35px;width:120px" value="Search"/>
<label>Name:</label><input type="text" id="txtName" name="txtName" />
<script>
$('#btnSearch').click(function () {
$.ajax({
url: '#Url.Action("TestAjax", "Home")',
data: { Name: $("#txtName").val() },
type: 'POST',
success: function (data) {
$("#divContent").html(data);
}
});
});
</script>
TestAjax.cshtml:
#ViewBag.Name
As #StephenMuecke pointed out in his comments, the libraries not being loaded correctly was the problem. While creating a new bundle of all libraries and adding it in the BundkeConfig.cs I had missed ~/Scripts/jquery.unobtrusive-ajax.js*. Got it working now.

Ajax.Beginform refreshing whole page

It redirects to whole new page instead of just updating the current one, I have unobtrusive scripts and web.config stuff. Why is this not working?
<div id="preview-image-placeholder"></div>
#foreach (var item in Model)
{
using (Ajax.BeginForm("PreviewImage/" + #item.Id.ToString(), "Music", null, new AjaxOptions { HttpMethod = "Post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "preview-image-placeholder" },
new { #enctype = "multipart/form-data", #item.Id }))
{
#Html.AntiForgeryToken()
<input type="file" class="upload-image" id="upload-image-file_#item.Id" name="file" accept="image/*">
<button class="btn btn-default" id="btn-preview_#item.Id" style="display: none" type="submit"></button>
}
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
Controller:
[ValidateAntiForgeryToken]
[HttpPost]
public PartialViewResult PreviewImage(HttpPostedFileBase file, int id)
{
//Do other code stuff
return PartialView("_DisplayImage", song);
}
_DisplayImage partial view:
#model IEnumerable<MusicSite.Models.UploadedSong>
#using MusicSite.CustomHtmlHelpers;
#foreach(var item in Model)
{
if (#item.CoverImageBytes != null)
{
#Html.ImageFor(x => item.CoverImageBytes, #item.SongName + " Image", new { #id = "preview-image" })
}
}
Besides unobtrusive scripts you must add Microsoft Ajax libraries too (MicrosoftAjax.js and MicrosoftMvcAjax.js) so that Ajax.BeginForm works correctly.
Regards,

MVC3 form posting with value and file

I am new to MVC3 and I would like to create a form with input column and file upload.
The problem comes when I try to do both thing at the same time.
Here is my code
...
[HttpPost]
public ActionResult About(string inputStr)
{
string local = inputStr;
string[] word = inputStr.Split(':');
return View();
}
[HttpPost]
public ActionResult GetFile(string inputStr, HttpPostedFileBase file)
{
string filename = file.FileName;
return RedirectToAction("About");
}
These two are my controllers
#using (Html.BeginForm("GetFile", "Home", (new { inputStr = "111" }), FormMethod.Post, new { enctype = "multipart/form-data" })){
<div class="editor">
<input type="file" name="file" />
<input type="submit" value="OK" id="submitFile" class="testingSubmit"/>
</div>
}
This code works well for uploading files, and sending string "111" to the controller.
Here is another jQuery function
$('.testingSubmit').click(function () {
var totalString="";
$('.editor-field :input').each(function () {
alert($(this).val());
totalString += $(this).val().toString() + ":";
});
$('form').submit();
/* $.post("About", { inputStr: totalString}, function (data) {
});*/
});
Here, what I am trying to do is the get the user input and put it on string totalString.
I was able to post the totalString to the controller by using $.post
My questions are:
1. Am i on the right track? i.e. Is that possible to do those two tasks together with one post?
2. If not, what are the possible solution for this?
Thank you very much for your attention and hopefully this can be solved!
I think something like this should work:
#using (Html.BeginForm("GetFile", "Home", (new { inputStr = "111" }), FormMethod.Post, new { #id = "frmGetFile", enctype = "multipart/form-data" })){
<div class="editor">
<input type="file" name="file" />
<input type="hidden" name="totalString" id="totalString"/>
<input type="submit" value="OK" id="submitFile" onclick="submitGetFileForm()" class="testingSubmit"/>
</div>
}
JavaScript:
function submitGetFileForm(e)
{
e.preventDefault();
var total = //build your total string here
$('#totalString').val(total);
$('#frmGetFile').submit();
}
Controller:
[HttpPost]
public ActionResult GetFile(string totalString, HttpPostedFileBase file)
{
// your action logic..
}

How to call success callback function of knockout model from AjaxForm in mvc

I'm a newbie in web. Now I'm learning mvc and i have a question. A have a knockout model and a Ajax.BeginForm. I can call "Todo" function as callback without error but it can't work when I try to use "success" function in model like (new AjaxOptions() { HttpMethod = "Post", OnSuccess = "LoginViewModel.success")
#using (Ajax.BeginForm("Todo", "Account", new AjaxOptions() { HttpMethod = "Post", OnSuccess = "Todo" }))
{
<input type="text" name="UserName" data-bind="value: name"/>
<br />
<input type="password" name="Password" data-bind="value: password"/>
<input type="submit"/>
}
<script type="text/javascript">
function LoginViewModel() {
var self = this;
self.name = ko.observable("Hello");
self.password= ko.observable("1234");
self.success = function () {
alert("Hello!");
};
}
ko.applyBindings(new LoginViewModel());
function Todo(data, status, xhr) {
alert("asd");
}
</script>
You should do the following:
var viewModel = new LoginViewModel();
ko.applyBindings(viewModel);
Then you can use:
(new AjaxOptions() { HttpMethod = "Post", OnSuccess = "viewModel.success")
You can see here that you need to create an object of the view model and then call the success method of the object.
I'd also recommend to just use jquery for the ajax calls instead of using the ajax in mvc.

How i can submit multiple objects inside the form post values to be added

i have a create view to add answers to a question, currently the user can only add one answer at the same time when he clicks on the submit button, instead of this i want the user to be able to insert multiple answers objects into the same view and then the system to add all these new answer objects to the database after the user click on the submit button, my current view looks as the follow:-
#model Elearning.Models.Answer
#{
ViewBag.Title = "Create";
}
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<div id = "remove">
#using (Ajax.BeginForm("Create", "Answer", new AjaxOptions
{
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "remove"
}))
{
<div id = "returnedquestion">
#Html.ValidationSummary(true)
<fieldset>
<legend>Answer</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
</fieldset>
<input type= "hidden" name = "questionid" value = #ViewBag.questionid>
<input type= "hidden" name = "assessmentid" value = #ViewBag.assessmentid>
<input type="submit" value="Add answer" />
</div>
}
</div>
and the action methods look as the follow:-
public ActionResult Create(int questionid)//, int assessmentid)
{
ViewBag.questionid = questionid;
Answer answer = new Answer();
return PartialView("_answer",answer);
}
//
// POST: /Answer/Create
[HttpPost]
public ActionResult Create(int questionid, Answer a)
{
if (ModelState.IsValid)
{
repository.AddAnswer(a);
repository.Save();
return PartialView("_details",a);
}
return View(a);}
so how i can modify the above code to be able to insert multiple answer objects at the same view and then submit these answers objects at the same time when the user click on the submit button?
Try Post a List
Add input by javascript when user click "Add Answer".
And when submit the form ,it will post all answer data to binding to List
<script>
$(document).ready(function () {
var anwserCount = 1;
$("#addbutton").click(function () {
$("#AnwsersDiv")
.append("<input type='text' name='Anwsers[" + anwserCount + "]'/>");
anwserCount += 1;
});
});
</script>
#using (Html.BeginForm())
{
<div id="AnwsersDiv">
<input type="text" name="Anwsers[0]" />
</div>
<input id="addbutton" type="button" value="Add answer" />
<input type="submit" value="submit" />
}
Model
public class Answer
{
public List<String> Anwsers { get; set; }
}
When submit the form
I think this is what you are looking for
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
Conclusion: you should make the post action with ICollection<Answer> Parameter, then it will be easy to get them when you post your main form, and create the appropriate QUESTION object, then save them all with only one submit.

Resources