How to get ID of element by using Html.BeginForm() - asp.net-mvc-3

I have the form and some code below.
#using (Html.BeginForm("Insert", "Question", "POST"))
{
<div id="add_tag">
<div id="list_tag">
<span class="post-tag" id="2">Phi kim<span class="delete-tag" title="Xóa Tag này"></span></span>
<span class="post-tag" id="22">Hóa Vô Cơ<span class="delete-tag" title="Xóa Tag này"></span></span>
<span class="post-tag" id="1">Lý<span class="delete-tag" title="Xóa Tag này"></span></span>
</div>
<div class="tag-suggestions hidden">
</div>
</div>
<div class="form-sumit clear">
<input type="submit" id="submit-button" value="Post your question" />
</div>
}
And my Insert action in QuestionController like this
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(FormCollection _form)
{
//my code here
}
I want to get id of span tag nested in by using Html.BeginForm and FormCollection. How can I do that? Plz someone help me. Thanks a lot.

When you click on submit button, form collects all input values inside this form and send to the server with the following format: inputId=inputValue. Span isn't the input control inside the form and form does not collect its value or another information to send to the server. You can generate hidden input control and set the id value to it. And then at the server side in the action you can get it from FormCollection.
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(FormCollection formCollection)
{
//for example all hidden input controls start with "hidden_tag" id
//and end with your number of tag:
var allNeededKeys = formCollection.AllKeys.Where(x => x.StartsWith("hidden_tag"));
var listOfId = allNeededKeys.Select(formCollection.Get).ToList();
}
Good luck.

I'm pretty sure you can't. You can use fiddler to see if they're posted back to the server but I don't think they are.

You should use hidden fields to post the span's id to the server.
Is the view strongly typed?

Related

Using remote attribute in .net core razor pages. The Parameter does not get value in Action Method of Controller

I am using Remote Attribute validation
The method is invoked successfully on textchange event. However, the parameters in the action method of the controller does not get the value of the field.
Here is the Action Method in the HomeController.cs. When invoked the Name parameter remains null. I will be pleased if someone solve this problem
[AcceptVerbs("Get", "Post")]
public async Task<ActionResult> IsExist(string Name)
{
List<Keywords> keywords = new List<Keywords>();
HttpClient client = _api.Initial();
HttpResponseMessage res = await client.GetAsync("api/Keywords");
if (res.IsSuccessStatusCode)
{
var result = res.Content.ReadAsStringAsync().Result;
keywords = JsonConvert.DeserializeObject<List<Keywords>>(result);
}
if (keywords.FirstOrDefault(x => x.Name == Name) == null)
{
return Json(false);
}
else
{
return Json(true);
}}
Here is the Model
public partial class Keywords
{
public int Id { get; set; }
[Display(Name = "Name of Keyword")]
[Required]
[Remote(action: "IsExist",controller: "Home", ErrorMessage = "Keyword already present!")]
public string Name { get; set; }}
Here is the razor page in which I want to implement validation
#page
#model Consumer.Pages.Keyword.CreateModel
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Keywords</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Keywords.Name" class="control-label"></label>
<input asp-for="Keywords.Name" class="form-control" />
<span asp-validation-for="Keywords.Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Keywords.Department" class="control-label"></label>
<select asp-for="Keywords.DepartmentId" class="form-control" asp-items="ViewBag.Department"></select>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-page="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
I found the solution. It is to
Remove partial in the model class definition.
Replace in the Razor Page
<input asp-for="Keywords.Name" class="form-control" />
with
<input asp-for="Keywords.Name" name="Name" class="form-control" />
The [Remote] attribute is all but useless. There's a long-standing problem from the ASP.NET MVC days that migrated its way into ASP.NET Core unabated, as well. Namely, the action that handles the remote must take a param that matches the input name of what what's being validated. In other words, your action takes a param, name, but what's being sent to it is Keywords.Name, which cannot bind to name. You'd have to do something like:
public async Task<ActionResult> IsExist(Keywords keywords)
And then, then the value will be available via keywords.Name. This obviously makes the usage highly dependent on the particular implementation, so if there's a situation with a different input name like Foo.Keywords.Name, then you'd need an entirely different action, to match that binding, and basically duplicate the logic (though you could factor out the majority the logic into some common method all the actions could utilize).
Long and short, you're probably better off just handling this yourself manually. Just bind to the input event on the name input, and then call your method via AJAX. Then you can explicitly control the key that's sent in the request body, such that it will always match your action. Just note that you'll also want to debounce sending that AJAX request so that it only happens every few keystrokes or so. Otherwise, you're going to hammer your action.

Thymeleaf th:field doesn't bind the value for input text

I want to send an object to the view for presentation and send it back to controller using springboot and Thymeleaf, however, I encounter a weird problem with Thymeleaf's th:value.
This is my controller:
#GetMapping("/food/buy/{fid}")
public String buyFood(HttpServletRequest request, #PathVariable("fid") Long fid, Model model) {
Food food = consumerService.getFood(fid);
System.out.println("foodid = " + food.getId());
model.addAttribute("food", food);
model.addAttribute("order", new OrderVO());
return "user/direct/f_order";
}
and my view:
<form th:action="#{/user/buy/direct/food}" method="post" th:object="${order}">
<table border="1px">
<tr th:hidden="true">
<td><input type="text" th:value="${food.id}" th:field="*{fid}" th:readonly="true"></td>
</tr>
</table>
</form>
and the VO class:
public class OrderVO {
private Long fid, address;
private Integer amount;
#DateTimeFormat(pattern = "HH:mm")
private Date deliverTime;
}
the problem is, the input field's value is null, but I'm sure that the food's id is not null (I print it in the controller)
I remove the th:field block, and the food.id can be properly presented. If I add the th:field block back, the problem reoccur.
So there may be something wrong with th:field, but I can't figure out. Can somebody point out my mistake?
===========================UPDATE============================
Some friends kindly points out that th:field may overwrite th:value, but I also use them in other views and it works fine:
<tr>
<td>UserName</td>
<td><input type="text" th:value="*{userName}" th:field="*{userName}"></td>
</tr>
The problem is getting incresing weird I think :(
Replace *{fid} with fid
My team had this same issue and it worked
In tabualr form try using th:name instead of th:field to overcome th binding issue
th:name="|order.fid|"
and stick to java naming convention.
Supposing you have to collect a comment to a page. You must transmit to the controller, besides the comment, the name of the page. Ofcourse, the user don't have to re-enter the name of this page. This information must be passed to controller, but th:field only map the values entered by the user, not the values generated by default.
But you can transmit the name of this page to controller as parameter in URL.
In html, you have something like that:
<form th:action="#{/saveComment(lastPage=${lastPage})}" th:object="${comments}" method="post" enctype="multipart/form-data">
<div class="row">
.................................................................................
<h2>Enter your comment</h2>
<textarea th:field="${comments.comment}" rows="10" cols="100" name="comment" id="comment"></textarea>
<label for="comment">Your comment here</label><br />
<input type="submit" name ="submit" value="Submit" />
</div>
</form>
In controller, you put stuff like this:
#PostMapping("/saveComment")
public String saveComment(Comments comments, String lastPage) {
comments.setPage_commented(lastPage);
commentsRepository.save(comments);
return "redirect:/";
}
It works fine to me.

Prevent reload on Ajax.BeginForm

How can I prevent page reloading when submitting form in partial view? There are a lot of examples but it seems that non of them is working for me. This is what I have. Partial view (Razor) which calls this:
#using (Ajax.BeginForm("SaveReply", "Home", null, new AjaxOptions { HttpMethod = "Post" }, new { target = "_self" }))
{
<div class="input-group wall-comment-reply" style="width:100%">
#Html.Hidden("eventid", #item.EventID)
<input name="txtReply" type="text" class="form-control" placeholder="Type your message here...">
<span class="input-group-btn">
<button class="btn btn-primary" id="btn-chat" type="submit">
<i class="fa fa-reply"></i> Reply
</button>
</span>
</div>
}
Then I have my action method in the controller:
[HttpPost]
public void SaveReply(string txtReply, string eventid)
{
//some code
}
The controller action is fired but after that it is automatically redirected to localhost/home/SaveReply
Maybe the problem is that this partial view is rendered from string. I took the code from:
How to render a Razor View to a string in ASP.NET MVC 3?
Also amongs other things i tried this:
http://geekswithblogs.net/blachniet/archive/2011/08/03/walkthrough-updating-partial-views-with-unobtrusive-ajax-in-mvc-3.aspx
I would appreciate any help.
I found the problem.
It seems that you need to reference the Unobtrusive scripts. Just install them from NuGet:
Install-Package Microsoft.jQuery.Unobtrusive.Ajax
And then reference it from the View that calls the Partial View:
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
And miraculosly it works without any other changes. More explanations can be found here:
[Why does Ajax.BeginForm replace my whole page?
and here:
[Why UnobtrusiveJavaScriptEnabled = true disable my ajax to work?
It seems that you need to use it if you are using Ajax.* helpers in MVC 3 and higher.

Error on submiting form MVC3 .Net

Hi there I have an error when I submit the following form:
<div id="tabs">
<ul>
<li>Project Details</li>
<li>Project Attachments</li>
<li><a href="#Url.Action("Members", "ProjectNetwork", new { IsTab = true })">Project
Network</a></li>
<li>Bulleting Board</li>
<li>Bids Received</li>
</ul>
</div>
<div id="LowerButton">
#Html.Hidden("MainStatus", #Model.Status)
#using (#Html.BeginForm("Dashboard", "Dashboard"))
{
<button type="button" id="MakeComment">
Make a Comment
</button>
<input type="submit" id="GoDashBoard" value="Return to Project List" />
}
</div>
When I press the button "GoDashBoard", The method "Dashboard" in the controller "Dashboard" is not reached. Instead the following error appears:
It tells me that a model property is beign sent to the server. However, there are no model properties inside the dashboard form.. unless I'm sending many forms at the same time. But I dont think thats possible right? Do you guys have any idea of why is trying to set a model property when I'm not actually sending any?
Update:
this is the input of the dashboard action:
public ActionResult Dashboard(int page = 1)
{
var user = (User)Session["User"];
if (user != null)
{...
}}
the input is a default integer. However, I saw the trace of the calls and its submiting another form which is not related to the one im using:
That form is inside of one of the ajax tabs. I dont understand how one form submits another form and they are not nested. Anyone knows a good workaround? because im thinking of receiving both forms in both actions and make some validations.
I solved it by removing the form "Dashboard" and instead adding an invisible link. The button would reference the invisible link:
#*#using (#Html.BeginForm("Dashboard", "Dashboard"))
{ *#
<button type="button" id="MakeComment">
Make a Comment
</button>
<button name="button" type="button" onclick="document.location.href=$('#GoDashBoard').attr('href')">Return to Project List</button>
<a id="GoDashBoard" href="#Url.Action("Dashboard", "Dashboard")" style="display:none;"></a>
#*<input type="submit" id="GoDashBoard" value="Return to Project List" />*#
#* }*#

How to pass array to controller?

I have form
#using (Html.BeginForm("Create", "StoreManager"))
{
#Html.ValidationSummary(true)
//etc..
}
User uploads images to server and when upload is completed immediately thumbnail image is creating and dynamically added to the form in this format:
<div class="gridItem">
<div><img src="image1.jpg" class="gridThumb" /></div>
<div class="gridTitle">
</div>
</div>
<div class="gridItem">
<div><img src="image2.jpg" class="gridThumb" /></div>
<div class="gridTitle">
</div>
</div>
my question is: how I can get list of all image files from this grid in controller action?
I want to save this list in model.
I guess you want save the images location and not the binary image itself.
Lets say your controller action looks like this
[HttpPost]
public ActionResult(string[] images)
{
// do something in images
}
I'm not sure how you generate your html, but you could also add a hidden field for each image like this :
<input type="hidden" name="images[0]" value="/Store/del?image1.jpg" />
<input type="hidden" name="images[1]" value="/Store/del?image2.jpg" />
Then when you post your form, you should receive the array on action parameter.
If you have another requirement, please let me know.

Resources