I have a Modal with 2 Tabs and I have an input on one of them. I need to pass the value of that input to the controller after clicking the search button. After that, the modal should stay. How can i pass the parameter to the controller without closing the modal?
<div class="modal-body">
#using (Html.BeginForm("SearchKuerzel", "Home"))
{
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="USZ-Kürzel" id="MyParameter" aria-label="USZ-Kürzel" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="submit">Mitarbeiter suchen</button>
</div>
</div>
}
</div>
You can either use javascript like #3xGuy has said or use jquery such as below:
$('#MyParameter').val();
to get the value and then use ajax to send information to the controller. From here can do whatever you want in the controller and just return Json such as below from the controller.
return Json(new {success = //true or false or whatever});
EDIT:
Once you have done what you want in the controller, you can return the value like I have returned the variable 'success' in the code above. In the result section of the ajax request you can get the data from the controller such as this:
//the rest of the ajax request
success: function(result)
{
//Change the value of html element to success in this case
$('#//id of the element').text(result.success)
}
EDIT 2:
To return two Json strings do as above but add another return such as:
return Json(new {string1 = //whatever, string2 = //whatever});
And in the ajax access them like:
success:function(result)
{
var return1= result.string1;
var return12 = result.string2;
}
Related
I have a list In my view. For each row, I view button and I am passing Id value as hidden. But when I click any button it is passing wrong hidden value to the controller. Always it passes the first-row hidden value to the controller.
View:
#foreach (var list in Model)
{
<div>
<div > #( ((int)1) + #Model.IndexOf(list)).</div>
<div >#list.details</div>
<div class="col-md-2 row-index">
<button class="btn btn-link" type="submit" name="action:view" id="view">View</button>
<input type="hidden" name="viewId" id="viewId" value="list.WId" />
</div>
</div>
}
Controller:
[HttpPost]
[MultipleButton(Name = "action", Argument = "view")]
public ActionResult ViewDetail(string viewId)
{
return RedirectToAction("ViewDetails");
}
To get all values you need to change the input value type in your controller to array of strings.
I hope that this solution can help you
[HttpPost]
[MultipleButton(Name = "action", Argument = "view")]
public ActionResult ViewDetail(string[] viewId)
{
return RedirectToAction("ViewDetails");
}
if you want to get the exact value you need to duplicate the form within your foreach
in this case you should write somthing like this :
#foreach (var list in Model)
{
<div>
<div > #( ((int)1) + #Model.IndexOf(list)).</div>
<div >#list.details</div>
<div class="col-md-2 row-index">
<form ... > // complete your form attributes
<button class="btn btn-link" type="submit" name="action:view" id="view">View</button>
<input type="hidden" name="viewId" id="viewId" value="list.WId" />
</form>
</div>
</div>
}
Note : You should delete the global form
You should have one form for each row. then you submit that row.
Otherwise as you state it passes first value.
You are setting each value to the same element ID (which is invalid anyway) and name. When you submit your form (which would be more helpful to fully answer your question) it is finding the first element that matches that criteria and submitting it.
There are multiple ways to resolve this such as the already mentioned form per entry but the other preference would be to modify you button to a div and add a click handler to pass the specific value to a js function which would then submit to the controller. Its a preference choice regarding how tightly coupled you want your front end. But the main problem is your element naming convention.
I want to send POST request to AdminController. But when i watch it in debugger, the request is GET.
<form method="post">
<input type="button" formmethod="post" onclick="location.href='#Url.Action("Index","Admin",new {rowID = #p.ProductID})'" value="Delete"/>
</form>
Because you wrote code to do a GET request on the submit button click !
onclick="location.href='#Url.Action("Index","Admin",new {rowID =
#p.ProductID})'"
Here you are setting the location.href value to the /Admin/Index and it will be a new GET request.
If you want to post, simply remove the onclick event on the button. If you want to send the ProductID value, you can keep that in a hidden input field inside your form and when you click submit the value of this form element will be also submitted.
#using(Html.BeginForm("Index","Admin"))
{
<input type="hidden" name="rowID" value="#p.ProductID" />
<input type="submit" value="Delete"/>
}
Assuming your HttpPost Index action method of AdminController has a parameter with same name as the input name to accept the productId.
[HttpPost]
public ActionResult Index(int rowID)
{
// to do : Return something
}
I want to call my method in my mvc view. I have a method called SavePersoon wich has to save the changed data into my database. This is my code from my services:
public bool SavePersoon(PersoonModel persoon)
{
bool result = true;
db.Persoon.AddOrUpdate(persoon.GetPoco());
db.SaveChanges();
return result;
}
This is the button who has to be pressed and then this code above has to deal the work itself.
The view:
<button type="button" id="btnSaveChanges" class="btn btn-primary">Opslaan</button>
Do I have to use something similair like <asp:LinkButton...?
You can make use of Ajax , Something like this
$("#btnSaveChanges").on("click",function(){
$.ajax({
url:"/controllerName/SavePersoon",
data:$("#formName").serialize(),
cache:false,
type:"POST",
error:function(){
alert("Error");
}
});
});
If you use Razor view engaine, you can make your method return an action result and call it from the view using Html.Actionlink.
You can do 2 things:
Use the HTML Helpers that ASP.Net MVC provides to create a form which posts to the required method, something like 'Save' of the controller 'Person':
#using (Html.BeginForm("Save", "Person", FormMethod.Post, new { #class = "form-horizontal" })) {
<div>
<!-- Your HTML, this could for example be a text field for the person its name -->
#Html.TextBoxFor(Model => Model.Name, new { #class = "form-control" })
<input type="submit" class="btn btn-primary" value="Save" />
</div>
}
This will create a form tag for you, something like <form action="person/save" method="post"> ... your HTML & the submit button ... </form>
An alternative is to use Ajax to prevent the page from refreshing as stated in the above post.
$("#btnSaveChanges").on("click",function(){
$.ajax({
url: '#Url.Action("Save", "Person")', // Again an MVC HTML Helper to create a URL
data:$("#Name").val(), // Posts the value of a text field with ID "Name"
cache:false,
type:"POST",
success: funcion(returnValue) {
// Do something with the result.
}
error:function(){
alert("Error");
}
});
});
I have a problem where I have a form in a Html.RenderAction and after submitting the form I have to reload the parent but I keep getting "Child actions can not perform redirect actions". So how can I solve it without Ajax etc.
In my parent I have:
#{
var UserReviewExist = Model.Reviews.FirstOrDefault(x => x.AspNetUser.UserName == Name.AspNetUser.UserName);
}
#{if (UserReviewExist == null)
{
Html.RenderAction("ReviewCreate", "Reviews", new { BookID = Model.Id });
}
}
My RenderAction View contains this:
#model Trigger_Happy_Bunnies.Models.Review
#{
Layout = null;
}
#{
if (true)
{
Trigger_Happy_Bunnies.Models.Review newReview = new Trigger_Happy_Bunnies.Models.Review();
<div style="border:1px black">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
and ends with
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
</div>
}
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
And lastly I have this in my controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ReviewCreate([Bind(Include = "Id,BookId,UserId,Text,Title,Rating,IsActive,IsReported,ReportedBy,ReportReason,ModifiedDate,ModifiedBy,CreatedDate")] Review review)
{
if (ModelState.IsValid)
{
db.Reviews.Add(review);
db.SaveChanges();
return View("~/Views/Reviews/ReviewCreate.cshtml");
}
ViewBag.UserId = new SelectList(db.AspNetUsers, "Id", "Email", review.UserId);
ViewBag.BookId = new SelectList(db.Books, "Id", "UserId", review.BookId);
return PartialView();
}
So how can I update the parent view when submitting the form?
I'm not sure what your issue is here. A child action merely dumps its response into the view. So at the end of the day, whether you used a child action, a partial or just plopped the code right in the view, you just have a one HTML document that includes a form.
Calling Html.BeginForm with no parameters says basically that it should use the current action, but even in the context of child action, that's still going to be the main action being rendered. So, your form will post to that main action, not your child action.
That's how it should be. You cannot post to a child action, because that makes no sense in the context of a web page. Technically, you can as long as it's not marked as [ChildActionOnly], but the entire page will change to the partial view that's returned as the response, sans layout. If you want to replace just the area that was rendered via the child action, you must submit an AJAX request that returns the partial response and manually replace the appropriate node in the DOM with that.
In other words, that's why a child action can't redirect. It's not a true action and it hasn't been routed to. It's not rendered until the response preparation phase, and by that point, there's already data in the response, preventing any changes, like a redirect. If you need to redirect after the post of the form, you should have that already in place, just make sure your main action has a version that handles post, and redirect from there.
My MVC view has a table with an editable field as follows.
<td>
<div class="view">
<%= Model.device_Url%>
</div>
<div class="edit">
<input type="text" name="deviceurl" id = "deviceurl" value="<%= Model.device_Url%>" />
</div>
</td>
The user has the option to edit then save the value entered in the above text box field.
<td class="options">
<div class="view">
Edit
</div>
<div class="edit">
Save
Cancel
</div>
</td>
I would like to call my controller /Live/Update and pass in the value changed in the text box in the URL.
How would I get the value entered inthe text box.
Do I need java script to do this?
You will need javascript unless you want to use a traditional submit.
The easiest approach would be to use jQuery and get the value with a line of code similar to this:
$("#deviceurl").val()
I would then make an ajax call to submit the value back to your controller's action. You also probably want to use the Url.Action helper to build the Url:
$.ajax(
url: '<%=Url.Action("Update")%>,
data : {deviceUrl : $("#deviceurl").val()},
success : function (result){
// handle logic when the update succeeds
}
);
Hope this helps
My advise will for you to use Html.ActionLink instead of using this Save
like this :
<%=Html.ActionLink("Save",
"Live", // <-- Controller Name.
"Update", // <-- ActionMethod
new { streamurl = deviceurl },
new { #class = "save refresh" }
)
%>