Ajax.BeginForm render wrong url in mvc - c#

I am trying to load a div data using ajax rather than whole view on post method.
but it returns object%20HTMLInputElement action name on post action.
Controller:
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(DemoCLass objdemo)
{
return View();
}
View
<div id="divEmp">
#using (Ajax.BeginForm("Index", "Challan", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divEmp" }))
{
#Html.AntiForgeryToken()
<h3 style="text-align:center;" class="row header">Challan Data</h3>
#Html.Partial("_DateCommonFT")
}
It includes _Layout.cshtml where i have defined scripts as:
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
How to render only post action without loading whole page (_layout.cshtml) on post request using ajax.

Can you try to close your div tag and receive HtmlForgeryToken in controller like following.
you can also fill your target div with PartialView by returning PartialView() in Index method
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(DemoCLass objdemo)
{
return PartialView();
}
<div id="divEmp">
</div>
#using (Ajax.BeginForm("Index", "Challan", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divEmp" }))
{
#Html.AntiForgeryToken()
<h3 style="text-align:center;" class="row header">Challan Data</h3>
#Html.Partial("_DateCommonFT")
}

please Ajax.Begin form you can use OnSuccess method.
In VIew:-
#using (Ajax.BeginForm("Index", "Challan", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divEmp", OnSuccess = "AjaxForm" }))
{
}
In Script:-
here return json from post controller.
function AjaxForm(response){
.....do as uou want...
}
in Controller:-
[HttpPost]
public ActionResult Index(DemoCLass objdemo)
{
return json(new {IsSuccess = true},JsonRequestBehavior.AllowGet);
}
if you have any query in this one then tell to me

Use the PartialView method to return a view without the layout.
[HttpPost]
public ActionResult Index(DemoCLass objdemo)
{
return PartialView();
}
If you want to return the html without layout markup only for the ajax form submissions, you can check the request headers to see whether the request is an xhr request or not. Request.IsAjaxRequest() method will be handy here.
[HttpPost]
public ActionResult Index(DemoCLass objdemo)
{
if (Request.IsAjaxRequest())
{
return PartialView();
}
else
{
return View();
}
}

Related

Redirect back with message after file upload MVC 4 c#

I've working on MVC 4 application and want to redirect back with message to call action view:
Action that called : Upload
Current view : Index
public class HospitalController: Controller {
public ActionResult Index()
{
return View(Model);
}
[HttpPost]
public ActionResult Index(Model model)
{
return View(ohosDetailFinal);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(HttpPostedFileBase upload,FormCollection form)
{
//Here i want to pass messge after file upload and redirect to index view with message
// return View(); not working
}
}
#using (Html.BeginForm("Upload", "Hospital", null, FormMethod.Post, new { enctype = "multipart/form-data", #class = "" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<input type="file" id="dataFile" name="upload" class="hidden" />
}
Thanks !
Follow the PRG pattern. After successful processing, redirect the user to another GET action.
You can return a RedirectResult using RedirectToAction method. This will return a 304 response to the browser with the new url in the location header and the browser will make a new GET request to that url.
[HttpPost]
public ActionResult Upload(HttpPostedFileBase upload,FormCollection form)
{
//to do : Upload
return RedirectToAction("Index","Hospital",new { msg="success"});
}
Now in the Index action, you may add this new parameter msg and check the value of this and show appropriate message. The redirect request will have a querystring with key msg (Ex :/Hospital/Index?msg=success)
public ActionResult Index(string msg="")
{
//to do : check value of msg and show message to user
ViewBag.Msg = msg=="success"?"Uploaded successfully":"";
return View();
}
and in the view
<p>#ViewBag.Msg</p>
If you do not prefer the querystring in the url, you may consider using TempData. But tempdata is available only for the next request.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(HttpPostedFileBase upload,FormCollection form)
{
//Here i want to pass messge after file upload and redirect to index view with message
return Index();//or with model index
}
Try the below code, Hope It helps.!
View
#using (Html.BeginForm("Upload", "Hospital", null, FormMethod.Post, new { enctype = "multipart/form-data", #class = "" }))
{
if (TempData["Info"] != null)
{
#Html.Raw(TempData["Info"])
}
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<input type="file" id="dataFile" name="upload" class="hidden" />
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(HttpPostedFileBase upload,FormCollection form)
{
//Here i want to pass messge after file upload and redirect to index view with message
TempData["Info"]="File Uploaded Successfully!";
return RedirectToAction("Index");
}

How to update partial view from another partial view via action results

I have three partial views on main view
on the first partial view I have search functionality and when user clicks on search I want to refresh results into 3rd partial view.
Controller:
public ActionResult Search()
{
virtualmodel vm = new virtualmodel();
return PartialView(svm);
}
[HttpPost]
public ActionResult Search(ViewModel svm)
{
// Query to retrive the result
// I am not sure what to return from here. Link to another action or just return back to same same partial
}
public ActionResult AnotherPartialPartial()
{
}
In main view
#{Html.RenderAction("Search", "Searchc");
}
How to do it? Do I need ajax?
Using ajax you can call a controller action and return it's response to a particular div.
Empty div:
<div class="row" id="div3">
</div>
Ajax to display html in empty div:
function performSearch(searchCriteria) {
//get information to pass to controller
var searchInformation = JSON.stringify(**your search information**);
$.ajax({
url: '#Url.Action("Search", "ControllerName")',//controller name and action
type: 'POST',
data: { 'svm': searchInformation } //information for search
})
.success(function (result) {
$('#div3').html(result); //write returned partial view to empty div
})
.error(function (xhr, status) {
alert(status);
})
}
jQuery will help you with it!
Try to handle submit button onclick event like this:
$("#yourButtonId").click(function()
{
$.ajax({
type: "POST",
url: "/yourUrl", //in asp.net mvc using ActionResult
data: data,
dataType: 'html',
success: function (result) {
//Your result is here
$("#yourContainerId").html(result);
}
});
});
You can do it with ajax.
First, change your html.beginform to ajax.beginform in your view and add div id into UpdateTargetId that you want to change contents. After updating first partial with ajax.beginform, you can update other partialviews with ajax.beginform's "OnSuccess" function. You have to add update function like that:
#using (Ajax.BeginForm("YourAction", "YourController",
new { /*your objects*/ }, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ChangeThisPart", OnSuccess = "OnSuccessMethod" }))
{
/*your code*/
}
<script>
function OnSuccessMethod() {
$("#YouWantToChangeSecondDivID").load('/YourController/YourAction2');
$("#YouWantToChangeThirdDivID").load('/YourController/YourAction3');
};
</script>
Then in your controller, return a partial view to refresh your view part that you entered it's ID in UpdateTargetId value:
public ActionResult YourControllerName(YourModelType model)
{
...//your code
return PartialView("_YourPartialViewName", YourViewModel);
}
Note: Don't forget to add reference to "jquery.unobtrusive-ajax.min.js" in your view while using ajax.
So, say you have your View with PartialView, which have to be updated by button click:
<div class="target">
#{ Html.RenderAction("UpdatePoints");}
</div>
<input class="button" value="update" />
There are some ways to do it. For example you may use jQuery:
<script type="text/javascript">
$(function(){
$('.button')click(function(){
$.post('#Url.Action("PostActionToUpdatePoints", "Home")').always(function(){
$('.traget').Load('/Home/UpdatePoints');
})
});
});
</script>
PostActionToUpdatePoints is your Action with [HttpPost] attribute, which you use to update points
If you use logic in your action UpdatePoints() to update points, maybe you forgot to add [HttpPost] attribute to it:
[HttpPost]
public ActionResult UpdatePoints()
{
ViewBag.points = _Repository.Points;
return PartialView("UpdatePoints");
}

Why Ajax doesn’t work? (ASP.NET MVC5)

I am doing a web application using ASP.NET MVC 5. It seems to me that I did everything as it goes, but ajax is just not working. I see results only after refreshing.
This is in my View:
#{
AjaxOptions ajaxOptions = new AjaxOptions {
UpdateTargetId = "CommmentList",
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace};
}
<div id="CommentList">
#using (Ajax.BeginForm("Index", "Comment", ajaxOptions))
{
// some content
<div>
#Html.Action("_AddCommentForItem", "Comment")
</div>
}
</div>
This is in a layout view:
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
EDIT:
These are actions in a Comment controller:
// GET: Comment
public async Task<ActionResult> Index()
{
var comments = db.Comments.Include(k => k.Item);
return View(await comments.ToListAsync());
}
// GET
public PartialViewResult _AddCommentForItem()
{
ViewBag.ItemId = new SelectList(db.Items, "Id", "Name");
return PartialView("_AddCommentForItem");
}
// POST
[HttpPost]
public PartialViewResult _AddCommentForItem ([Bind(Include = "Id,ItemId,CommentContent")] Comment comment)
{
if (ModelState.IsValid)
{
db.Comments.Add(commment);
db.SaveChanges();
}
ViewBag.ItemId = new SelectList(db.Items, "Id", "Name", comment.ItemId);
return PartialView("_AddCommentForItem");
}
}
}
I included partial view _AddCommentForItem, which is creating a comment, in an index view of the Comment controller. That's way i want the result to be visible right away, without refreshing.
What am I missing?
Thank you.

MVC submit button not firing

I am using ASP.net MVC 4 with the Razor engine.
I have a page (Index.cshtml) and a controller (HomeController.cs)
I am trying to hook up my submit button to an Action Result in my controller - however i can't seem to get it to fire.
My HTML :
#using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post))
{
<div class="main-Background">
******lots of other html here*******
<button type="submit" id="btnSave">Save</button>
</div>
}
My Controller :
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
[HttpPost]
public ActionResult SubmitForm()
{
return View();
}
}
At the moment i havn't implemented a model to pass the values through to the controller, i just wanted to see if i could get the ActionResult SubmitForm to fire.
I have tried #using (Html.BeginForm()) with no parameters, i have also tried including [HttpPost] above my ActionResult, without any luck.
Edit i have also tried using <input type="submit" id="btnSave">Save</input> instead of a button.
Not sure where i am going wrong
It turns out that jQuery was stopping the ActionResult from being hit.
I had a button click event which was "eating up" the ActionResult functionality. I solved this by calling my ActionResult using Ajax.
You dont need to use "-Controller" suffix. Use just Home instead of HomeController, MVC will convert it for you.
Use
#using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post, new { id = "submitForm" }))
instead of
#using (Html.BeginForm("SubmitForm", "HomeController", FormMethod.Post, new { id = "submitForm" }))
Full codes
view
#using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post, new { id = "submitForm" }))
{
<div class="main-Background">
******lots of other html here*******
<input type="submit" id="btnSave">Save</input>
</div>
}
And controller
[HttpPost]
public ActionResult SubmitForm()
{
return View();
}
View:
#using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post))
{
<div class="main-Background">
******lots of other html here*******
<button type="submit" id="btnSave">Save</button>
</div>
}
Controller:
[HttpPost]
public ActionResult SubmitForm()
{
return View();
}
May be the problem is occurred because of other HTML inside your div so check it out. Otherwise it works perfectly.
You need to add Html.BeginForm with the parameters. Here is an example:
ActionName – Name of the Action. In this case the name is Create.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
http://localhost:60386//Home/Create
#using (Html.BeginForm("Create", "Home", FormMethod.Post))
{
#Html.EditorFor(model => model.FirstName)
<input type="submit" value="Create"/>
}
HomeController.cs:
[HttpPost]
public ActionResult Create(Person person)
{
if (ModelState.IsValid)
{
db.Persons.Add(person);
db.SaveChanges();
return RedirectToAction("Create");
}
return View(person);
}
TL;DR
I had [Required] data attributes on my view model preventing the submit from working when the form wasn't filled.
I had two submit buttons in my MVC code, one for Submit, the other for Cancel.
Both buttons were firing correctly on data entry, but neither when nothing was entered.
It took me a bit to realize that my view model had [Required] field validations in place!
View:
#using (Html.BeginForm(actionName: "Index", controllerName: "User", method: FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.TextBoxFor(m => m.PhoneNumber)
...
<input type="submit" name="submitAction" value="Verify" />
<input type="submit" name="submitAction" value="Cancel" />
}
ViewModel:
public class UserViewModel
{
[Required]
[MaxLength(10)]
public string PhoneNumber { get; set; }
[Required]
...
}
Controller Method:
[HttpPost]
[ValidateAntiForgeryToken()]
public ActionResult Index(UserViewModel viewModel, string submitAction)
{
switch(submitAction)
{
case "Verify": ...
case "Cancel": ...
}
}
Change this #using (Html.BeginForm("SubmitForm", "HomeController", FormMethod.Post, new { id = "submitForm" }))
to
#using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post, new { id = "submitForm" }))
Explanation : No need to suffix Controller anywhere, it being accepted by default
and in the Controller
[HttpPost]
public ActionResult SubmitForm(string id)
{
return View();
}
Explanation : as the Form Method given by you is Post so need to include [HttpPost] before the Action and the parameter you were passing was missing in the action method

MVC4 - Register is partial view but on success should Redirect to a new Full Page

I have a Partial View for Register.
#using (Ajax.BeginForm("Register",
new AjaxOptions { HttpMethod = "post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "loginForm" }))
The Controller:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
Guid activationGUID = Guid.NewGuid();
if (UserManager.Register(model.Email, model.FullName, model.Password, activationGUID))
return RedirectToAction("Index", "Dashboard");
else
ModelState.AddModelError("", "This email already exists");
}
return PartialView(model);
}
On error,
I want the partial view to show the error message
The controller calls return PartialView(model); ...and that works !!!
On success,
I want the entire page to refresh (instead than the UpdateTargetId specified on the ajax call).
The controller calls return RedirectToAction("Index", "Dashboard"); ...and that fails !!!
Instead I'm getting the Dashboard form inserted into the UpdateTargetID.
What am I doing wrong???
You need to use OnSuccess method and choose if you want to replace div content or change window.location

Categories

Resources