MVC How to change a buttons text on submit - asp.net-mvc

I'm trying to create a simple MVC 4 app with a few buttons that when clicked adds one to their text value. The problem is when I use < input > buttons I can't change the text value when I submit the form and when I use < button > then there is nothing passed to the action.
I have a simple SQL Database that the controller hits which is where the initial ViewData values are coming from and how it's storing the buttons current value.
Also I'm currently trying to do this with multiple forms but if it is possible with one form then that would be ideal.
#using (Ajax.BeginForm("AddOne", "Home", null, new AjaxOptions { UpdateTargetId = "btn-tc-top"}, new { #class = "rectangle-top" }))
{
<input type="submit" class="button" name="button" id="btn-tc-top" value="#ViewData["ct-t"]"/>
}
#using (Ajax.BeginForm("AddOne", "Home", null, new AjaxOptions { UpdateTargetId = "btn-tc-bottom"}, new { #class = "rectangle-bottom" }))
{
<button type="submit" class="button" name="button" id="btn-tc-bottom">#ViewData["ct-b"]</button>
}

You could subscribe to the OnSuccess handler:
#using (Ajax.BeginForm("AddOne", "Home", new { id = "btn-tc-top" }, new AjaxOptions { OnSuccess = "addSuccess" }, new { #class = "rectangle-top" }))
{
<input id="btn-tc-top" class="button" type="submit" name="button" value="#ViewData["ct-t"]" />
}
#using (Ajax.BeginForm("AddOne", "Home", new { id = "btn-tc-bottom" }, new AjaxOptions { OnSuccess = "addSuccess" }, new { #class = "rectangle-bottom" }))
{
<input id="btn-tc-bottom" class="button" type="submit" name="button" value="#ViewData["ct-b"]" />
}
which could be defined like this:
function addSuccess(result) {
$('#' + result.id).val(result.text);
}
and the controller:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["ct-t"] = "1";
ViewData["ct-b"] = "2";
return View();
}
[HttpPost]
public ActionResult AddOne(string id, int button)
{
return Json(new { id = id, text = button + 1 });
}
}

Related

Image upload using #Ajax.BeginForm in .NET MVC?

I want to upload image using Ajax.BeginForm in my application.
Currently HttpPostedFileBase file is getting value 0. Anyone Please guide me here.
I have tried this code but file is not uploading.
Appreciated, if anyone can provide some solutions for this. If I use #Html.BeginForm then It works but I want to use #Ajax.BeginForm.
Model
public class ClsUpload
{
public string FilePath { get; set; }
}
Controller
public ActionResult Edit(ClsUpload model,HttpPostedFileBase file)
{
if (Request.Files.Count > 0)
{
file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
string path = Path.Combine(Server.MapPath("/Content/Images/"), fileName);
file.SaveAs(path);
model.FilePath = path;
}
}
try
{
UploadDetials details = new UploadDetials();
details.UpdateDetails(model);
return RedirectToAction("Index");
}
catch
{
return RedirectToAction("Index");
}
}
Partial View
#model XX.X.Models.File.ClsUpload
#using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "partial", InsertionMode = InsertionMode.Replace }))
{
#Html.HiddenFor(model => model.FilePath)
<input type="file" name="file" />
<img src=#Model.FilePath alt="Image" />
<input type="submit" value="Save" />
}
You can update your code with FormMethod.Post, new { enctype = "multipart/form-data" }) and [AcceptVerbs(HttpVerbs.Post)] as follow
In Partial View
#using (Html.BeginForm("ActionMethod1", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
}
In Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ActionMethod1(HttpPostedFileBase pic)
{
}
This is old, but I want to show how I have accomplished uploading a file using Ajax.BeginForm(). Basically, the overloads will tell you what is possible. I use the overload for: "string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes". Note: I use null for "routeValues".
Here is a code example:
#using (Ajax.BeginForm("UploadFile", "Home", null, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "MyIDToUpdate", OnSuccess = "EditSuccessClearForm('IDToClear', '')", OnFailure = String.Format("NewGenericFailure(xhr, '{0}')", "#IDToPassThisFunction"), InsertionMode = InsertionMode.ReplaceWith }, new { enctype = "multipart/form-data", #id = "NewFileFormID" }))
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-sm-8 col-sm-offset-1">
#Html.TextBox("file", "", new { type = "file", accept = ".jpg, .jpeg, .png, .pdf", #id = fileID, onchange = VerifySizeOfFile })
</div>
<div class="col-sm-2">
<button type="submit" id="FileSubmitButton" class="btn btn-primary">Upload</button>
</div>
</div>
}

Ajax.beginForm not posting Files to Controller

I am working on MVC. I have a form to send Email. The razor form is below
#Ajax.BeginForm("sendEmail", "communication", new AjaxOptions() { OnBegin = "return onBeginFun();", UpdateTargetId = "emailMessage" }, new { id = "communicationForm", enctype = "multipart/form-data" })
{
#Html.TextAreaFor(m => m._Email.Body, new { #class = "form-control editor overflow:scroll; max-height:300px", name = "emailbody", id = "emailbody" })
<input type="file" id="fileUploader" name="fileUploader" multiple ;" />
<button type="submit" id="submitCommunication"> SAVE>>></button>
}
The controller is as follows
[HttpPost]
[ValidateInput(false)]
public async Task<JsonResult> sendEmail(CommunicationModelView P_CMV, HttpPostedFileBase fileUploader)
{
....................
}
Upon clicking submit button I can see the Model filled with the form data, but fileUploader is null even though I have selected file(s).
Need help.
Thanks in advance.

Can't trigger my controllers action with a date time in the route values

Here is my form. If I remove the classdate parameter it works fine, but I can't trigger the controller if I have a date in the routevalues
using (Html.BeginForm("Results", "Home", new { classDate = DateTime.Now }, FormMethod.Get, new { #class = "navbar-form navbar-left", role = "search" }))
{
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" id="navbarSearchQueryWithin" name="location">
</div>
<button type="submit" class="btn btn-default">Submit</button>
}
Here is my controller
[HttpGet]
public ActionResult Results(string navbarSearchQueryWithin, DateTime classDate)
{
var viewModel = new YogaSpaceListViewModel
{
SearchQuery = navbarSearchQueryWithin
};
return View("Search", viewModel);
}

Cancel button on MVC

When the client click on Cancel (on ItemsOptions) he should go back to the previous page (Client):
I added in the View ItemsOptions:
#using (Html.BeginForm("","", FormMethod.Post, new { #class = "form-group", role = "form" }))
{
<div class="col-md-4"><input id = "theCancel" class="cancel" type="submit" value="Cancel" /></div>
}
When the Button Cancel is hit the error Message :
The required anti-forgery form field "__RequestVerificationToken" is not present.
I added in the controller
[ValidateAntiForgeryToken]
public ActionResult ***Client***(OrderItems model)
{
}
and in the Client View
#using (Html.BeginForm("Client", "Home", FormMethod.Post, new { #class = "form-group", role = "form" }))
{
#Html.AntiForgeryToken();
}
I tried another way:
I added in the View ItemsOptions:
#using (Html.BeginForm("","", FormMethod.Post, new { #class = "form-group", role = "form" }))
{
<div class="col-md-4"><input class="btn btn-warning" type="submit" value="Cancel" name="action:Cancel" /></div>
}
the controller
[MultipleButton(Name = "action", Argument = "Cancel")]
public ActionResult Cancel(OrderItems model)
{
return View("Client", model);
}
How can I implement the cancel button in the MVC form,I want the user to go to the previous page.
Thanks
If you just want the cancel button to go back
<script type='text/javascript'>
function goBack() {
window.history.back();
}
</script>
<!--cancel button-->
<button onclick='goBack()'>Cancel</button>
Does something like this work for you?

How to display a model state error in case I am returning a partial view

I have the following action method for creating new network info:-
public ActionResult CreateVMNetwork(int vmid)
{
VMAssignIps vmips = new VMAssignIps()
{
TechnologyIP = new TechnologyIP() { TechnologyID = vmid},
IsTMSIPUnique = true,
IsTMSMACUnique = true
};
return PartialView("_CreateVMNetwork",vmips);
}
[HttpPost]
public ActionResult CreateVMNetwork(VMAssignIps vmip)
{
if (ModelState.IsValid)
{
try
{
repository.InsertOrUpdateVMIPs(vmip.TechnologyIP,User.Identity.Name);
repository.Save();
return PartialView("_networkrow",vmip);
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, "Error occurred: " + ex.InnerException.Message);
}
}
return PartialView("_CreateVMNetwork", vmip);
}
And I have the following _CreateVMNetwork view:-
#model TMS.ViewModels.VMAssignIps
#using (Ajax.BeginForm("CreateVMNetwork", "VirtualMachine", new AjaxOptions
{
InsertionMode = InsertionMode.InsertAfter,
UpdateTargetId = "networktable",
LoadingElementId = "loadingimag",
HttpMethod= "POST"
}))
{
#Html.ValidationSummary(true)
#Html.HiddenFor(model=>model.TechnologyIP.TechnologyID)
#Html.Partial("_CreateOrEditVMNetwork", Model)
<input type="submit" value="Save" class="btn btn-primary"/>
}
and _CreateOrEditVMNetwork view:-
#model TMS.ViewModels.VMAssignIps
<div>
<span class="f">IP Address</span>
#Html.EditorFor(model => model.TechnologyIP.IPAddress)
#Html.ValidationMessageFor(model => model.TechnologyIP.IPAddress)
<input type="CheckBox" name="IsTMSIPUnique" value="true" #(Html.Raw(Model.IsTMSMACUnique ? "checked=\"checked\"" : "")) /> |
<span class="f"> MAC Address</span>
#Html.EditorFor(model => model.TechnologyIP.MACAddress)
#Html.ValidationMessageFor(model => model.TechnologyIP.MACAddress)
<input type="CheckBox" name="IsTMSMACUnique" value="true" #(Html.Raw(Model.IsTMSMACUnique ? "checked=\"checked\"" : "")) />
</div>
The problem I am facing is that in case there is a model state error when adding a new entity, a partial view will be displayed with the model state error as follow:-
So my question is , if there is a way to display the model state error with the partial view , without updating the table row “insert after” as I am doing currently?
Thanks
Given the age i'm guessing you have already found a solution to this,
But here is an example using InsertionMode.Replace, maybe it can help someone else.
Snipped from view
#using (Ajax.BeginForm("AddPerson", "Home", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "UpdateSection" }))
{
<div id="UpdateSection">
#Html.Partial("PersonModel", Model.Person)
</div>
<input type="submit" value="add" />
}
Snipped from the controller
if (!ModelState.IsValid)
{
return PartialView("AddPerson", Person);
}
just make sure the "jquery.unobtrusive-ajax.min.js" script is included (i'm not sure it is by default)

Resources