Post ID doesn't Work in Form - asp.net-mvc-3

I have a post where I define a new database entity. After user enters needed values and submits the form, I insert the entity and post it back to the same page and display it's ID. When I enter the ID area disabled and readonly as below, it works perfectly.
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
ID:
#Html.TextBoxFor(model => model.ID, new { disabled = "disabled", #readonly = "readonly" })
<p><input type="submit" name="submit" value="Create" /></p>
</fieldset>
}
However, when I enter it only readonly as in below, it does insert the entity, but doesn't view the ID.
#Html.TextBoxFor(model => model.ID, new { #readonly = "readonly" })
I have another submit in the form, which uses the entities ID. However, I cannot use disabled here with the ID area, as it doesn't post the ID value. What can I do to resolve the issue?

You can enable the disabled field just before submitting. So, keep the ID field disabled. Now, enable it on submit. ie; if you submit the form on "myButton" click, add this in document.ready():
$('#myButton').click(function(e)
{
e.preventDefault();
$("#ID").removeAttr('disabled');
$('form').submit();
});

Instead of using html extensions, I directly wrote:
<input type="text" name="ID" value="#Model.ID" readonly />
And it works like a charm.

Related

Unable to to see Required message on the radio buttons fields in the MVC.NET Core application

I have a radio buttons field and I try tome make this field required. However, no matter what I try after I click the Submit button, no Required field message shows up on the page
Here is the radio button field
<div class=" form-group">
<div class="bisformdynamiclabel"></div>
<br />
#Html.RadioButtonFor(model => model.BIS232Request.JSONData.OwnershipActivity.Ownership, "Yes", new { id = "OwnershipAnswer_true", onclick = "displayOwnershipFieldsRow(true)" })
<label for="OwnershipAnswer_true">Yes</label>
#Html.RadioButtonFor(model => model.BIS232Request.JSONData.OwnershipActivity.Ownership, "No", new { id = "OwnershipAnswer_false", onclick = "displayOwnershipFieldsRow(false)" })
<label for="OwnershipAnswer_false">No</label>
</div>
Here is the code in the Model
[Required(ErrorMessage = "Please select Yes or No for the Ownership")]
public string Ownership { get; set; }
Other fields are validated without any issues. Can someone please tell what I am doing wrong?
You don't have anything actually displaying the messages. Specifically, you need something like:
#Html.ValidationMessageFor(m => m.BIS232Request.JSONData.OwnershipActivity.Ownership)
Or using the tag helper:
<span asp-validation-for="BIS232Request.JSONData.OwnershipActivity.Ownership"></span>

Ajax.BeginForm preload data

I have this view and everything fine with Ajax.BeginForm:
<h2>Index</h2>
#using (Ajax.BeginForm("Search", new AjaxOptions {
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "users"
})) {
<input name="q" type="text" />
<input type="submit" value="Search" />
}
<div class="table-responsive" id="users">
</div>
But, i have a little question.
Right now, when i open this page, there are no table with data - it loads only when form is submitted.
So, my question: is it possible to have preload data (without adding other code)?
When page is loaded, i would like to have already all data without filtering (input uses for filtering when value is typed and form submitted).
Just call your Search action from users div when the page loads. You may not specify any parameter or use the default one. I assume you have something like this:
public ActionResult Search(string q)
{
var users = _usersRepository.GetAll();
if(!string.IsNullOrEmpty(q))
users = users.Where(user => string.Equals(user.Name, q));
return PartialView("_Search", users);
}
And in the view:
<div class="table-responsive" id="users">
#Html.Action("Search")
</div>

How do I refresh a second partial view, after the first partial view is updated?

I have a page which has a partial view (it's a login form). When the submit button is clicked, it calls the controller and logs the person in and refreshes the login form to show that he is logged in.
I now need to update the portion of the screen that shows the login button, or if he is logged in, shows "Hello, Logged In user"
I have a partial view written that shows whether or not the person is logged in, but I don't know how to call it after the success of the first one. I know there is an OnSuccess event, and that seems to be where I would wire that up, but I am not sure how to do this.
#using (Ajax.BeginForm("Login", "Account", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "loginSection", }))
{
<div id="loginSection">
...form omitted for clarity.
<input type="submit" value="Log in" />
</div>
}
This is the partial view that needs to be updated after the login.
<ul id="menu">
#if (Request.IsAuthenticated)
{
<text>
Hello, #User.Identity.Name
</text>
}
else
{
<ul>
<a onclick="openLoginWindow()">Login</a>
<a onclick="openRegisterWindow()">Register</a>
</ul>
}
Instead of using Ajax.BeginForm, use normal form and do the form posting with your custom code so that you can controll the success handler as you wish
<div id="login">
#using(Html.Beginform())
{
<input type="text" name="UserName" />
<input type="text" name="Password" />
<input type="submit" id="btnLogin" />
}
</div>
and the script which will listen to the submit button click event and send the form the action method.
$(function(){
$("#btnLogin").click(function(e){
e.preventDefault();
var _this=$(this);
var _form=_this.closest("form");
$.post(_form.attr("action"),_form.serialize(),function(res){
if(res.Status==="authenticated")
{
//Let's hide the login form
$("#login").hide();
$("#yourSecondDiv").html(res.PartialViewContent);
}
else
{
alert("Wrong password");
}
});
});
});
So the javascript code is expecting a JSON structure like below from the controller action
{
"Status":"Authenticated",
"PartialViewContent" : "<p>The markup you want to show</p>"
}
the PartialViewContent will hold the markup you want to show to the user.
public ActionResult Login(string UserName,string Password)
{
//to do : Build the JSON and send it back
}
This answer will tell you how send the markup of a partial view in a JSON property to client.
Here is what worked for me:
Added OnSuccess:
#using (Ajax.BeginForm("Login", "Account", new AjaxOptions {
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "loginSection",
OnSuccess = "successfulLogin"
}))
{... details omitted.
Then added this:
function successfulLogin() {
$('#loginPartial').load('Account/LoginLinksPartial');
which calls in the controller:
public ActionResult LoginLinksPartial()
{
return PartialView("_LoginLinks");
}

How to send each element's ID from Ajax form to action?

I need that, which item I click, to send it's Id to GetProduct() action. I used hidden element, but it does not work:
#using (Ajax.BeginForm("GetProduct", "Product", new AjaxOptions { UpdateTargetId = "getProductResult" }, new { id = "productForm" }))
{
foreach (var item in list)
{
#item.Name
//this hidden always send '1', but I want to send item's Id
<input type="hidden" id='product_#(item.Id)' name ="id" value="#item.Id" />
}
<noscript>
<input type="submit" id="sendButton" />
</noscript>
}
Where is my wrong? How can I send Id ?
the hidden input have name "id" and it is getting added number of time in for loop.
Hence it will not work..
don't submit the form directly on click of button. store the ID in rel attribute of button.
and assign its value to hidden variable when it gets clicked and then submit the form..
<a href="#"
rel="#(item.id)"
onclick="$('#id').val($(this).attr('rel')); ('#productForm').trigger('submit');">
#item.Name
</a>
putting the onClick code in separate function would be preffered though :)
Check this Fiddler
Try this .
foreach (var item in list)
{
#using (Ajax.BeginForm("GetProduct", "Product", new AjaxOptions { UpdateTargetId = "getProductResult" }, new { }))
{
<a href="#" class="anchor" >#item.Name</a>
//this hidden always send '1'.
<input type="hidden" id='product_#(item.Id)' name ="id" value="#item.Id" />
<noscript>
<input type="submit" id="sendButton" />
</noscript>
}
}
<script>
$(function(e){
$('.anchor').click(function(e){
//get the parent form.
var parentform= $(this).parents('form:first');
parentform.submit();
});
});
</script>

How to get ID of element by using Html.BeginForm()

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?

Resources